您的位置:首页 > 其它

无刷新上传解析csv文件

2010-06-25 11:35 134 查看
 前阵子工作中用到,贴上代码,仅保留上传有关的代码,发现code其实很少。

解析csv文件

private DataTable ImportDataTable(string filepath)
{
DataTable mydt = new DataTable("myTableName");
mydt.Columns.Add("Data ID", System.Type.GetType("System.String"));
mydt.Columns.Add("Field Name", System.Type.GetType("System.String"));
mydt.Columns.Add("New Value", System.Type.GetType("System.String"));
DataRow mydr;
using (System.IO.StreamReader mysr = new System.IO.StreamReader(filepath))
{
int data;
char current;
StringBuilder text = new StringBuilder();

IDictionary<int, List<string>> results = new Dictionary<int, List<string>>();
bool isInYinHao = false; ;
int lineId = 1;
int index = 0;
while (true)
{
data = mysr.Read();
if (data != -1)
{
current = (char)data;
if (current == '"')
{
if (isInYinHao)
{
isInYinHao = false;
}
else
{
if (index > 0)
{
text.Append(current);
}

isInYinHao = true;
}
}
else if (current == ',')
{
if (isInYinHao)
{
text.Append(current);
}
else
{

SaveResult(results, lineId, text);
index = 0;
continue;
}
}
else if (current == '\r')
{
if (isInYinHao)
{
text.Append(current);
}
}
else if (current == '\n')
{
if (isInYinHao)
{
text.Append(current);
}
else
{
SaveResult(results, lineId, text);
index = 0;
lineId++;
continue;
}
}
else if (current == '\0')
{
}
else
{
text.Append(current);
}

index++;
}
else
{
//Read to file end.
SaveResult(results, lineId, text);
break;
}
}

foreach (int id in results.Keys)
{
mydr = mydt.NewRow();
for (int i = 0; i < results[id].Count; i++)
{
if (i > 2)
{
break;
}

mydr[i] = results[id][i];
}

mydt.Rows.Add(mydr);
}

}

return mydt;
}

private void SaveResult(IDictionary<int, List<string>> results, int lineId, StringBuilder text)
{
if (!results.ContainsKey(lineId))
{
results.Add(lineId, new List<string>());
}

results[lineId].Add(text.ToString());
text.Remove(0, text.Length);
}


点击下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: