原创经典[CSV→DataSet]类
一个解析CSV file的经典函数。曾尝试用odbc直接处理csv文件,发现虽然很好用,但数据量一但大的话会出现许多错误,要解决的问题很多,诸如字符编码问题:必须utf-8→ansi;某些column不显示的问题(绝对妖- -!!!)等。寻遍各大站点,鲜有现成的solution,BB给的在codeproject上的又比较复杂- -!!!,于是自己动手写了一个...方便易用。感觉用起来很爽,故特此拿出来share:public DataSet GetDataSetFromCSV(string filePath, string fileName)
{
StreamReader reader = new StreamReader(filePath + "\\" + fileName);
string str;
DataTable dt = new DataTable();
int max_column = 0;
while ((str = reader.ReadLine()) != null)
{
string[] split = str.Split(',');
int column_num = 0;
foreach (string unitstr in split)
{
column_num = column_num + 1;
}
if (column_num > max_column)
{
int j = column_num - max_column;
max_column = column_num;
while (j != 0)
{
j = j - 1;
dt.Columns.Add();
}
}
DataRow dr = dt.NewRow();
int i = 0;
foreach (string unitstr in split)
{
dr = unitstr;
i = i + 1;
}
dt.Rows.Add(dr);
}
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}
页:
[1]