C#读取CSV文件的四种方法

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      } 

转载于:https://www.cnblogs.com/yuanlei347/archive/2009/07/17/1525773.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值