CSV是以文本形式保存的表格数据,具体是每列数据使用逗号分割,每行数据使用CRLF( )来结尾,如果数据值包含逗号或CRLF则使用双引号将数值包裹,如果数据值包含双引号则使用两个双引号做为转义。
public static class Common { public static DataTable CSVToDataTable(string path) { //第一行是否为列名 bool firstColumnIsName = false; //文件读取的位置信息 int current = 0; //当前是否为一个值的开始处 bool isNewValueBegin = true; //当前是否为双引号范围 bool isDoubleMarkMange = false; //存储数据 List<List<string>> datatable = new List<List<string>>(); #region 解析文件 using (FileStream fs = new FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite)) { using (System.IO.StreamReader sr = new StreamReader(fs, Encoding.Default)) { List<string> row = new List<string>(); string csv = sr.ReadToEnd(); string temp = ""; while (current < csv.Length) { char buffer = csv[current]; bool bufferNextExist = current + 1 < csv.Length; char bufferNext = '