using CsvHelper; using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Text; namespace JinYuan.Helper { public class CSVHelper { /// /// 读取CSV文件 /// /// csv文件名 /// public static List ReadCSV(string fileName, string strSeparator = "\t") { if (!File.Exists(fileName)) return null; //Nuget获取CsvHelper using (var reader = new StreamReader(fileName, Encoding.Default)) { var cfg = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture) { Mode = CsvMode.Escape, Escape = '\\', Delimiter = strSeparator//设置分隔符号 }; using (var csv = new CsvReader(reader, cfg)) { var list = csv.GetRecords().ToList(); return list; } } } /// /// 写入CSV文件 /// /// csv文件名 /// public static bool WriterCSV(string fileName, List records) { try { FileStream Log = null; if (!Directory.Exists(fileName)) Directory.CreateDirectory(fileName); string file = (fileName + DateTime.Now.ToString("yyyyMMdd")) + ".csv"; var cfg = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture); if (!File.Exists(file)) { Log = new FileStream(file, FileMode.Create); } else { cfg.HasHeaderRecord = false;//是否将第一行作为标题 } if (Log != null) { Log.Close(); } //Nuget获取CsvHelper using (var writer = new StreamWriter(file, true, Encoding.Default)) { using (var csv = new CsvWriter(writer, cfg)) { csv.WriteRecords(records); writer.Flush(); return true; } } } catch (Exception ex) { throw ex; } } /// /// 写入指定列表CSV文件 /// /// /// /// /// /// public static bool WriterCSV(string directory, string fileName, string title, string content) { FileStream fs = null; StreamWriter sw = null; try { if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } string fullFileName = $@"{directory}\{fileName}"; if (!File.Exists(fullFileName)) { fs = new FileStream(fullFileName, FileMode.Create, FileAccess.Write); sw = new StreamWriter(fs, Encoding.UTF8); sw.WriteLine(title); } else { fs = new FileStream(fullFileName, FileMode.Append, FileAccess.Write); sw = new StreamWriter(fs, Encoding.UTF8); } sw.WriteLine(content); sw.Close(); fs.Close(); return true; } catch (Exception ex) { sw?.Close(); fs?.Close(); } return false; } /// /// 获取当天的日期的文件 /// /// /// public static List FindTodayFile(string CurrPath) { try { if (!Directory.Exists(CurrPath)) { return null; } DirectoryInfo di = new DirectoryInfo(CurrPath); FileInfo[] ffis = di.GetFiles(); string today = DateTime.Now.Year.ToString().Substring(0, 4) + DateTime.Now.Month.ToString("0#") + DateTime.Now.Day.ToString("0#"); List listFilePath = new List(); for (int i = 0; i < ffis.Length; i++) { FileInfo tmp = ffis[i]; if (tmp.Name.Substring(0, 8) == today) { listFilePath.Add(tmp.FullName); } } return (listFilePath.Count > 0) ? listFilePath : null; } catch (Exception ex) { throw ex; } } /// /// /// /// /// public static List FindHostFile(string CurrPath, DateTime date) { try { if (!Directory.Exists(CurrPath)) { return null; } DirectoryInfo di = new DirectoryInfo(CurrPath); FileInfo[] ffis = di.GetFiles(); string today = date.ToString().Substring(0, 4) + date.Month.ToString("0#") + date.Day.ToString("0#"); //var result1 = Regex.Replace(date, @"[^0-9]+", ""); //string today = result1.Substring(0,8); List listFilePath = new List(); for (int i = 0; i < ffis.Length; i++) { FileInfo tmp = ffis[i]; if (tmp.Name.Substring(0, 8) == today) { listFilePath.Add(tmp.FullName); } } return (listFilePath.Count > 0) ? listFilePath : null; } catch (Exception ex) { throw ex; } } /// /// 导出到CSV文件 /// /// 报表DataTable /// 导出路径 /// 输出信息 /// 自定义的列名称,以','英文逗号分隔 /// 表名,一般为空 /// 是否导出成功 public static bool ExportDataTableToCSV(DataTable table, string filePath, out string msg, string columnName = null, string tableHeader = null) { try { string dirPath = Path.GetDirectoryName(filePath); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath);//文件的父目录不存在就创建新目录 } bool IsAppend = false; //false为创建 true为追加 if (File.Exists(filePath)) { IsAppend = true;//如果文件存在就不写入表头 } using (FileStream _stream = new FileStream(filePath, FileMode.Create | FileMode.Append, FileAccess.Write)) { StreamWriter _writer = new StreamWriter(_stream, Encoding.UTF8); if (tableHeader != null) { _writer.WriteLine(tableHeader); } if (columnName != null && !IsAppend) { _writer.WriteLine(columnName); } else if (columnName == null && !IsAppend) { List columnNameList = new List(); foreach (DataColumn dc in table.Columns) { columnNameList.Add(dc.ColumnName); } _writer.WriteLine(string.Join(",", columnNameList)); } for (int i = 0; i < table.Rows.Count; i++) { for (int j = 0; j < table.Columns.Count; j++) { _writer.Write(table.Rows[i][j].ToString()); _writer.Write(","); } _writer.WriteLine(); } _writer.Close(); msg = "导出CSV文件成功"; return true; } } catch (Exception ex) { msg = string.Format("导出CSV文件失败,原因:{0}", ex.Message); return false; } } /// /// 导出报表为Csv /// /// DataTable /// 物理路径 /// 表头 /// 字段标题,逗号分隔 public static bool dt2csv(DataTable dt, string strFilePath, string tableheader, string columname) { try { string strBufferLine = ""; StreamWriter strmWriterObj = new StreamWriter(strFilePath, false, System.Text.Encoding.UTF8); strmWriterObj.WriteLine(tableheader); strmWriterObj.WriteLine(columname); for (int i = 0; i < dt.Rows.Count; i++) { strBufferLine = ""; for (int j = 0; j < dt.Columns.Count; j++) { if (j > 0) strBufferLine += ","; strBufferLine += dt.Rows[i][j].ToString(); } strmWriterObj.WriteLine(strBufferLine); } strmWriterObj.Close(); return true; } catch { return false; } } /// /// 将Csv读入DataTable /// /// csv文件路径 /// 表示第n行是字段title,第n+1行是记录开始 public static DataTable csv2dt(string filePath, int n, DataTable dt) { StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8, false); int i = 0, m = 0; reader.Peek(); while (reader.Peek() > 0) { m = m + 1; string str = reader.ReadLine(); if (m >= n + 1) { string[] split = str.Split(','); System.Data.DataRow dr = dt.NewRow(); for (i = 0; i < split.Length; i++) { dr[i] = split[i]; } dt.Rows.Add(dr); } } return dt; } } }