1.首先(NPOI官网下载dll)
添加引用:NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,NPOI.OpenXmlFormats.dll
2.代码——CSVHelper
1 public class CSVHelper 2 { 3 /// <summary> 4 /// 写入CSV 5 /// </summary> 6 /// <param name="fileName">文件名</param> 7 /// <param name="dt">要写入的datatable</param> 8 public static void WriteCSV(string fileName,DataTable dt) 9 { 10 FileStream fs; 11 StreamWriter sw; 12 string data = null; 13 14 //判断文件是否存在,存在就不再次写入列名 15 if (!File.Exists(fileName)) 16 { 17 fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); 18 sw = new StreamWriter(fs, Encoding.UTF8); 19 20 //写出列名称 21 for (int i = 0; i < dt.Columns.Count; i++) 22 { 23 data += dt.Columns[i].ColumnName.ToString(); 24 if (i < dt.Columns.Count - 1) 25 { 26 data += ",";//中间用,隔开 27 } 28 } 29 sw.WriteLine(data); 30 } 31 else 32 { 33 fs = new FileStream(fileName, FileMode.Append, FileAccess.Write); 34 sw = new StreamWriter(fs, Encoding.UTF8); 35 } 36 37 //写出各行数据 38 for (int i = 0; i < dt.Rows.Count; i++) 39 { 40 data = null; 41 for (int j = 0; j < dt.Columns.Count; j++) 42 { 43 data += dt.Rows[i][j].ToString(); 44 if (j < dt.Columns.Count - 1) 45 { 46 data += ",";//中间用,隔开 47 } 48 } 49 sw.WriteLine(data); 50 } 51 sw.Close(); 52 fs.Close(); 53 } 54 55 56 57 /// <summary> 58 /// 读取CSV文件 59 /// </summary> 60 /// <param name="fileName">文件路径</param> 61 public static DataTable ReadCSV(string fileName) 62 { 63 DataTable dt = new DataTable(); 64 FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); 65 StreamReader sr = new StreamReader(fs, Encoding.UTF8); 66 67 //记录每次读取的一行记录 68 string strLine = null; 69 //记录每行记录中的各字段内容 70 string[] arrayLine=null; 71 //分隔符 72 string[] separators = { "," }; 73 //判断,若是第一次,建立表头 74 bool isFirst = true; 75 76 //逐行读取CSV文件 77 while ((strLine = sr.ReadLine()) != null) 78 { 79 strLine = strLine.Trim();//去除头尾空格 80 arrayLine = strLine.Split(separators, StringSplitOptions.RemoveEmptyEntries);//分隔字符串,返回数组 81 int dtColumns = arrayLine.Length;//列的个数 82 83 if (isFirst) //建立表头 84 { 85 for (int i = 0; i < dtColumns; i++) 86 { 87 dt.Columns.Add(arrayLine[i]);//每一列名称 88 } 89 } 90 else //表内容 91 { 92 DataRow dataRow = dt.NewRow();//新建一行 93 for (int j = 0; j < dtColumns; j++) 94 { 95 dataRow[j] = arrayLine[j]; 96 } 97 dt.Rows.Add(dataRow);//添加一行 98 } 99 } 100 sr.Close(); 101 fs.Close(); 102 103 return dt; 104 }
原文地址:https://www.cnblogs.com/LY-HeroesRebor/p/9359743.html
时间: 2024-11-05 11:33:36