C#讀取CSV檔案的四種方法

來源:互聯網
上載者:User

Code 1:

用一個System.Web.UI.HtmlControls.HtmlInputFile去handle檔案選取。

以下是button  click  event中的code,用來執行當檔案選取了之後讀取檔案的內容。

1      System.Web.HttpPostedFile input = Request.Files[0];
2
3      if (input != null && input.ContentLength != 0)
4      {
5        string path = input.FileName.ToString();
6        System.IO.StreamReader reader = new System.IO.StreamReader(path);
7
8        reader.Peek();
9        while (reader.Peek() > 0)
10        {
11          string str = reader.ReadLine();
12          string[] split = str.Split(',');
13          if (split[0] != "" && split[1] != "")
14          {
15            System.Data.DataSet ds = new DataSet();
16            System.Data.DataRow dr = ds.Tables[0].NewRow();
17            dr[0] = split[0];
18            dr[1] = split[1];
19            ds.Tables[0].Rows.Add(dr);
20          }
21        }
22      }

CODE 2:

剛剛做過,直接當表來讀

SELECT  *
 INTO  theImportTable
 FROM
 OPENROWSET('MSDASQL',
 'Driver={Microsoft  Text  Driver  (*.txt;  *.csv)};DEFAULTDIR=D:;Extensions=CSV;',
 'SELECT  *  FROM  CSVFile.csv')

CODE 3:

OPENROWSET('MSDASQL',
 'Driver={Microsoft  Text  Driver  (*.txt;  *.csv)};DEFAULTDIR=D:;Extensions=CSV;',
 'SELECT  *  FROM  CSVFile.csv')

好複雜哦

檔案當作一個資料庫來操作,使用ole驅動

CODE 4:

1      int intColCount = 0;
2      DataTable mydt = new DataTable("myTableName");
3
4      DataColumn mydc;
5      DataRow mydr;
6
7      string strpath = "";
8      string strline;
9      string[] aryline;
10
11      System.IO.StreamReader mysr = new System.IO.StreamReader(strpath);
12
13      while ((strline = mysr.ReadLine()) != null)
14      {
15        aryline = strline.Split(new char[] { '|' });
16
17        intColCount = aryline.Length;
18        for (int i = 0; i < aryline.Length; i++)
19        {
20          mydc = new DataColumn(aryline[i]);
21          mydt.Columns.Add(mydc);
22        }
23
24        mydr = mydt.NewRow();
25        for (int i = 0; i < intColCount; i++)
26        {
27          mydr[i] = aryline[i];
28        }
29        mydt.Rows.Add(mydr);
30      } 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.