CSV 檔案讀寫

來源:互聯網
上載者:User

標籤:

轉自:http://www.cnblogs.com/Clin/archive/2013/03/14/2959022.html

  1 public 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             else103             {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 }

 

CSV 檔案讀寫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.