您的位置:首页 > 其它

用流读写csv文件

2016-05-18 15:40 417 查看
http://www.cnblogs.com/Clin/archive/2013/03/14/2959022.html

报错:没有权限对路径 xxx 的访问被拒绝。

解决:不能到文件夹 要指定为文件名

DataTable dt = new DataTable();

var filePath="@c:/";
FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
StreamReader sr = new StreamReader(fs, Encoding.UTF8);

//excel中每一行的数据
string strLine = "";

//记录每行中各字段的内容
string[] aryLine = null;
string[] tableHead = null;

//判断是否为第一行
bool IsFirst = true;

//计算列数
int columnCount = 0;

while ((strLine = sr.ReadLine())!=null)
{
if (IsFirst)
{
tableHead = strLine.Split(',');
IsFirst = false;
columnCount = tableHead.Length;
//创建列
for (var i = 0; i < strLine.Length - 1; i++)
{
DataColumn dc = new DataColumn(tableHead[i]);
dt.Columns.Add(dc);
}
}
else
{
aryLine = strLine.Split(',');
DataRow dr = dt.NewRow();
for (int j = 0; j < columnCount; j++)
{
dr[j] = aryLine[j];
}
dt.Rows.Add(dr);
}
if (aryLine != null && aryLine.Length > 0)
{
dt.DefaultView.Sort = tableHead[0] + " " + "asc";
}
sr.Close();
fs.Close();
return dt;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息