標籤:turn options reader return dtc csv datatable else app
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 }
C#中使用NPOI匯入匯出CSV檔案