C#读取csv格式文件

方法1:用一个System.Web.UI.HtmlControls.HtmlInputFile去handle文件选取

以下是button  click  event中的code,用来执行当文件选取了之后读取文件的内容

System.Web.HttpPostedFile input = Request.Files[0];

if (input != null && input.ContentLength != 0)
{
string path = input.FileName.ToString();
System.IO.StreamReader reader = new System.IO.StreamReader(path); reader.Peek();
while (reader.Peek() > 0)
{
string str = reader.ReadLine();
string[] split = str.Split(',');
if (split[0] != "" && split[1] != "")
{
System.Data.DataSet ds = new DataSet();
System.Data.DataRow dr = ds.Tables[0].NewRow();
dr[0] = split[0];
dr[1] = split[1];
ds.Tables[0].Rows.Add(dr);
}
}
}

方法2:当成SQL的数据表来读取

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

方法3:文件当做一个数据库读取,使用Ole驱动

int intColCount = 0;
DataTable mydt = new DataTable("myTableName"); DataColumn mydc;
DataRow mydr; string strpath = "";
string strline;
string[] aryline; System.IO.StreamReader mysr = new System.IO.StreamReader(strpath); while ((strline = mysr.ReadLine()) != null)
{
  aryline = strline.Split(new char[] { '|' });   intColCount = aryline.Length;
  for (int i = 0; i < aryline.Length; i++)
  {
    mydc = new DataColumn(aryline[i]);
    mydt.Columns.Add(mydc);
  }   mydr = mydt.NewRow();
  for (int i = 0; i < intColCount; i++)
  {
    mydr[i] = aryline[i];
  }
  mydt.Rows.Add(mydr);
} 

  

上一篇:[LeetCode]题解(python):069-Sqrt(x)


下一篇:【MySQL解惑笔记】Navicat 无法远程连接MySQL数据库