在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
/// <summary> /// 将DataTable中数据写入到CSV文件中 /// </summary> /// <param name="dt">提供保存数据的DataTable</param> /// <param name="fileName">CSV的文件路径</param> public static bool SaveCSV(DataTable dt, string fullPath) { try { FileInfo fi = new FileInfo(fullPath); if (!fi.Directory.Exists) { fi.Directory.Create(); } FileStream fs = new FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write); //StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default); StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8); string data = ""; //写出列名称 for (int i = 0; i < dt.Columns.Count; i++) { data += "\"" + dt.Columns[i].ColumnName.ToString() + "\""; if (i < dt.Columns.Count - 1) { data += ","; } } sw.WriteLine(data); //写出各行数据 for (int i = 0; i < dt.Rows.Count; i++) { data = ""; for (int j = 0; j < dt.Columns.Count; j++) { string str = dt.Rows[i][j].ToString(); str = string.Format("\"{0}\"", str); data += str; if (j < dt.Columns.Count - 1) { data += ","; } } sw.WriteLine(data); } sw.Close(); fs.Close(); return true; } catch { return false; } } /// <summary> /// 读取CSV文件到DataTable中 /// </summary> /// <param name="filePath">CSV的文件路径</param> /// <returns></returns> public static DataTable ReadCSV(string filePath) { DataTable dt = new DataTable(); int lineNumber = 0; using (CsvFileReader reader = new CsvFileReader(filePath)) { CsvRow row = new CsvRow(); while (reader.ReadRow(row)) { if (0 == lineNumber) { foreach (string s in row) { dt.Columns.Add(s.Replace("\"", "")); } } else { int index = 0; DataRow dr = dt.NewRow(); foreach (string s in row) { dr[index] = s.Replace("\"", ""); index++; } dt.Rows.Add(dr); } lineNumber++; } } return dt; }
|
请发表评论