按格式读取csv文件内容
2014-07-12 13:50
411 查看
string path = @"C:\Users\keen_\Downloads\upload\upload\Upload\20140701141934_export.csv"; ImportDataTable(path); //2014-07-01 //get csv file to datatable private static 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 static 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); }
相关文章推荐
- 内容写到 csv 格式的文件中 及 读取 csv 格式的文件内容
- 如何读取csv文件的内容
- 用Excel打开csv文件时,如何处理数字内容展现会自动转换格式的问题
- PHP读取csv文件的内容
- NET(C#)中将DATATABLE内容写入到CSV文件 与 将CSV文件内容读取到DATATABLE中
- 如何读取csv文件的内容
- 读取csv文件内容到DataTable
- java读取csv文件内容示例代码
- 读取csv文件数据内容进行图形绘制(vc++描述)
- 读取csv文件内容
- vba中读取utf-8格式的csv文件保证不乱码
- .NET中读取csv文件内容
- 读取并显示 CSV 文件的整个内容
- golang语言实现读取csv文件内容,把相同的内容提取到另外一个文件
- C格式读取文件内容
- 用Excel打开csv文件时,如何处理数字内容展现会自动转换格式的问题
- NET(C#)中将DataTable内容写入到CSV文件 与 将CSV文件内容读取到DataTable中(原创)
- 如何读取csv文件的内容
- C#读取csv格式文件
- 基于PHP读取csv文件内容的详解