读取CSV文件的几种方式

只做记录,没做过详细分析,用过数据连接,貌似还不错,别的方法没用过。

1.数据连接方式:

根据连接方式的不同,又分成几种:

  • ODBC方式:会自动将第一行作为行头去掉,而且无法设置不去掉第一行。

代码
/// <summary>
/// 获取CSV导入的数据,不带后缀名
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="fileName">文件名称(.csv不用加)</param>
/// <returns></returns>
public DataTable GetCsvData(string filePath, string fileName)
{
string path = Path.Combine(filePath, fileName);
string connString = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + filePath + ";Extensions=asc,csv,tab,txt;";
try
{
using (OdbcConnection odbcConn = new OdbcConnection(connString))
{
odbcConn.Open();
OdbcCommand oleComm
= new OdbcCommand();
oleComm.Connection
= odbcConn;
oleComm.CommandText
= "select * from [" + fileName + "]";
OdbcDataAdapter adapter
= new OdbcDataAdapter(oleComm);
DataSet ds
= new DataSet();
adapter.Fill(ds, fileName);
odbcConn.Close();
_dataSource
= ds.Tables[0];
return _dataSource;
}
}
catch (Exception ex)
{
throw ex;
}
}

  • OleDb方式,可以设置是否忽略第一行,HDR=Yes则忽略第一行。

 

代码
connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+filePath+";Extended Properties='text;HDR=No;FMT=Delimited'";
try {
using (OleDbConnection oledbConn = new OleDbConnection(connString))
{
oledbConn.Open();
OleDbCommand oleComm
= new OleDbCommand();
oleComm.Connection
= oledbConn;
oleComm.CommandText
= "select * from [" + fileName + "]";
OleDbDataAdapter adapter
= new OleDbDataAdapter(oleComm);
DataSet ds
= new DataSet();
adapter.Fill(ds, fileName);
oledbConn.Close();
_dataSource
= ds.Tables[0];
return ds.Tables[0];
}
}

 

 

经测试,这两种方法都可以,不知道有没有差别。

具体数据连接方式参见:http://www.connectionstrings.com/textfile

 

2.文件流方式:

代码
public static List<String[]> ReadCSV(string filePathName)
{
List
<String[]> ls = new List<String[]>();
StreamReader fileReader
=new StreamReader(filePathName);
string strLine="";
while (strLine != null)
{
strLine
= fileReader.ReadLine();
if (strLine != null && strLine.Length>0)
{
ls.Add(strLine.Split(
','));
}
}
fileReader.Close();
return ls;
}

3.TextFileParser的方式:

代码
private void subImportCSV_FileIo(string strFile)
{
Microsoft.VisualBasic.FileIO.TextFieldParser TF
= new Microsoft.VisualBasic.FileIO.TextFieldParser(strFile, Encoding.GetEncoding("GB2312"));
TF.Delimiters
= new string[] { "," }; //设置分隔符
string[] strLine;
while (!TF.EndOfData)
{
try
{
strLine
= TF.ReadFields();
//开始导入数据库,这个地方要排除行头
}
catch
{
}
}
TF.Close();
}
posted @ 2010-08-25 16:04  lightwalker  阅读(898)  评论(0编辑  收藏  举报