1public class CSVFileHelper 2{ 3 /// <summary> 4 /// 将DataTable中数据写入到CSV文件中 5 /// </summary> 6 /// <param name="dt">提供保存数据的DataTable</param> 7 /// <param name="fileName">CSV的文件路径</param> 8 public static void SaveCSV(DataTable dt, string fullPath) 9 { 10 FileInfo fi = new FileInfo(fullPath); 11 if (!fi.Directory.Exists) 12 { 13 fi.Directory.Create(); 14 } 15 FileStream fs = new FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write); 16 //StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default); 17 StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8); 18 string data = ""; 19 //写出列名称 20 for (int i = 0; i < dt.Columns.Count; i++) 21 { 22 data += dt.Columns[i].ColumnName.ToString(); 23 if (i < dt.Columns.Count - 1) 24 { 25 data += ","; 26 } 27 } 28 sw.WriteLine(data); 29 //写出各行数据 30 for (int i = 0; i < dt.Rows.Count; i++) 31 { 32 data = ""; 33 for (int j = 0; j < dt.Columns.Count; j++) 34 { 35 string str = dt.Rows[i][j].ToString(); 36 str = str.Replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号 37 if (str.Contains(',') || str.Contains('"') 38 || str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中 39 { 40 str = string.Format("\"{0}\"", str); 41 } 42 43 data += str; 44 if (j < dt.Columns.Count - 1) 45 { 46 data += ","; 47 } 48 } 49 sw.WriteLine(data); 50 } 51 sw.Close(); 52 fs.Close(); 53 DialogResult result = MessageBox.Show("CSV文件保存成功!"); 54 if (result == DialogResult.OK) 55 { 56 System.Diagnostics.Process.Start("explorer.exe", Common.PATH_LANG); 57 } 58 } 59 60 /// <summary> 61 /// 将CSV文件的数据读取到DataTable中 62 /// </summary> 63 /// <param name="fileName">CSV文件路径</param> 64 /// <returns>返回读取了CSV数据的DataTable</returns> 65 public static DataTable OpenCSV(string filePath) 66 { 67 Encoding encoding = Common.GetType(filePath); //Encoding.ASCII;// 68 DataTable dt = new DataTable(); 69 FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); 70 71 //StreamReader sr = new StreamReader(fs, Encoding.UTF8); 72 StreamReader sr = new StreamReader(fs, encoding); 73 //string fileContent = sr.ReadToEnd(); 74 //encoding = sr.CurrentEncoding; 75 //记录每次读取的一行记录 76 string strLine = ""; 77 //记录每行记录中的各字段内容 78 string[] aryLine = null; 79 string[] tableHead = null; 80 //标示列数 81 int columnCount = 0; 82 //标示是否是读取的第一行 83 bool IsFirst = true; 84 //逐行读取CSV中的数据 85 while ((strLine = sr.ReadLine()) != null) 86 { 87 //strLine = Common.ConvertStringUTF8(strLine, encoding); 88 //strLine = Common.ConvertStringUTF8(strLine); 89 90 if (IsFirst == true) 91 { 92 tableHead = strLine.Split(','); 93 IsFirst = false; 94 columnCount = tableHead.Length; 95 //创建列 96 for (int i = 0; i < columnCount; i++) 97 { 98 DataColumn dc = new DataColumn(tableHead[i]); 99 dt.Columns.Add(dc); 100 } 101 } 102 else 103 { 104 aryLine = strLine.Split(','); 105 DataRow dr = dt.NewRow(); 106 for (int j = 0; j < columnCount; j++) 107 { 108 dr[j] = aryLine[j]; 109 } 110 dt.Rows.Add(dr); 111 } 112 } 113 if (aryLine != null && aryLine.Length > 0) 114 { 115 dt.DefaultView.Sort = tableHead[0] + " " + "asc"; 116 } 117 118 sr.Close(); 119 fs.Close(); 120 return dt; 121 } 122} 123 124/// 给定文件的路径,读取文件的二进制数据,判断文件的编码类型 125/// <param name="FILE_NAME">文件路径</param> 126/// <returns>文件的编码类型</returns> 127 128public static System.Text.Encoding GetType(string FILE_NAME) 129{ 130 System.IO.FileStream fs = new System.IO.FileStream(FILE_NAME, System.IO.FileMode.Open, 131 System.IO.FileAccess.Read); 132 System.Text.Encoding r = GetType(fs); 133 fs.Close(); 134 return r; 135} 136 137/// 通过给定的文件流,判断文件的编码类型 138/// <param name="fs">文件流</param> 139/// <returns>文件的编码类型</returns> 140public static System.Text.Encoding GetType(System.IO.FileStream fs) 141{ 142 byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 }; 143 byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 }; 144 byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM 145 System.Text.Encoding reVal = System.Text.Encoding.Default; 146 147 System.IO.BinaryReader r = new System.IO.BinaryReader(fs, System.Text.Encoding.Default); 148 int i; 149 int.TryParse(fs.Length.ToString(), out i); 150 byte[] ss = r.ReadBytes(i); 151 if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF)) 152 { 153 reVal = System.Text.Encoding.UTF8; 154 } 155 else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00) 156 { 157 reVal = System.Text.Encoding.BigEndianUnicode; 158 } 159 else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41) 160 { 161 reVal = System.Text.Encoding.Unicode; 162 } 163 r.Close(); 164 return reVal; 165} 166 167/// 判断是否是不带 BOM 的 UTF8 格式 168/// <param name="data"></param> 169/// <returns></returns> 170private static bool IsUTF8Bytes(byte[] data) 171{ 172 int charByteCounter = 1; //计算当前正分析的字符应还有的字节数 173 byte curByte; //当前分析的字节. 174 for (int i = 0; i < data.Length; i++) 175 { 176 curByte = data[i]; 177 if (charByteCounter == 1) 178 { 179 if (curByte >= 0x80) 180 { 181 //判断当前 182 while (((curByte <<= 1) & 0x80) != 0) 183 { 184 charByteCounter++; 185 } 186 //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X 187 if (charByteCounter == 1 || charByteCounter > 6) 188 { 189 return false; 190 } 191 } 192 } 193 else 194 { 195 //若是UTF-8 此时第一位必须为1 196 if ((curByte & 0xC0) != 0x80) 197 { 198 return false; 199 } 200 charByteCounter--; 201 } 202 } 203 if (charByteCounter > 1) 204 { 205 throw new Exception("非预期的byte格式"); 206 } 207 return true; 208}
C# CSV文件读写
Stella981
2021-10-11
1487 0 0
点赞
收藏
评论区
加载中...