Wpf 导出CSV文件

 1  /// <summary>
 2         /// 将DataTable中数据写入到CSV文件中
 3         /// </summary>
 4         /// <param name="dt">提供保存数据的DataTable</param>
 5         /// <param name="fileName">CSV的文件路径</param>
 6         public static void SaveCSV(DataTable dt)
 7         {
 8             SaveFileDialog objSFD = new SaveFileDialog() { DefaultExt = "csv", Filter = "CSV Files (*.csv)|*.csv|Excel XML (*.xml)|*.xml|All files (*.*)|*.*", FilterIndex = 1 };
 9             if (objSFD.ShowDialog() == true)
10             {
11                 string strFormat = objSFD.FileName;
12                 FileInfo fi = new FileInfo(strFormat);
13                 if (!fi.Directory.Exists)
14                 {
15                     fi.Directory.Create();
16                 }
17                 FileStream fs = new FileStream(strFormat, System.IO.FileMode.Create, System.IO.FileAccess.Write);
18                 //StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
19                 StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
20                 string data = "";
21                 //写出列名称
22                 for (int i = 0; i < dt.Columns.Count; i++)
23                 {
24                     data += dt.Columns[i].ColumnName.ToString();
25                     if (i < dt.Columns.Count - 1)
26                     {
27                         data += ",";
28                     }
29                 }
30                 sw.WriteLine(data);
31                 //写出各行数据
32                 for (int i = 0; i < dt.Rows.Count; i++)
33                 {
34                     data = "";
35                     for (int j = 0; j < dt.Columns.Count; j++)
36                     {
37                         string str = dt.Rows[i][j].ToString();
38                         str = str.Replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号
39                         if (str.Contains(',') || str.Contains('"')
40                             || str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中
41                         {
42                             str = string.Format("\"{0}\"", str);
43                         }
44 
45                         data += str;
46                         if (j < dt.Columns.Count - 1)
47                         {
48                             data += ",";
49                         }
50                     }
51                     sw.WriteLine(data);
52                 }
53                 sw.Close();
54                 fs.Close();
55            56             }
57 
58         }
 1   /// <summary>
 2     /// 将CSV文件的数据读取到DataTable中
 3     /// </summary>
 4     /// <param name="fileName">CSV文件路径</param>
 5     /// <returns>返回读取了CSV数据的DataTable</returns>
 6     public static DataTable OpenCSV(string filePath)
 7     {
 8         Encoding encoding = Common.GetType(filePath); //Encoding.ASCII;//
 9         DataTable dt = new DataTable();
10         FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
11         
12         //StreamReader sr = new StreamReader(fs, Encoding.UTF8);
13         StreamReader sr = new StreamReader(fs, encoding);
14         //string fileContent = sr.ReadToEnd();
15         //encoding = sr.CurrentEncoding;
16         //记录每次读取的一行记录
17         string strLine = "";
18         //记录每行记录中的各字段内容
19         string[] aryLine = null;
20         string[] tableHead = null;
21         //标示列数
22         int columnCount = 0;
23         //标示是否是读取的第一行
24         bool IsFirst = true;
25         //逐行读取CSV中的数据
26         while ((strLine = sr.ReadLine()) != null)
27         {
28             //strLine = Common.ConvertStringUTF8(strLine, encoding);
29             //strLine = Common.ConvertStringUTF8(strLine);
30 
31             if (IsFirst == true)
32             {
33                 tableHead = strLine.Split(',');
34                 IsFirst = false;
35                 columnCount = tableHead.Length;
36                 //创建列
37                 for (int i = 0; i < columnCount; i++)
38                 {
39                     DataColumn dc = new DataColumn(tableHead[i]);
40                     dt.Columns.Add(dc);
41                 }
42             }
43             else
44             {
45                 aryLine = strLine.Split(',');
46                 DataRow dr = dt.NewRow();
47                 for (int j = 0; j < columnCount; j++)
48                 {
49                     dr[j] = aryLine[j];
50                 }
51                 dt.Rows.Add(dr);
52             }
53         }
54         if (aryLine != null && aryLine.Length > 0)
55         {
56             dt.DefaultView.Sort = tableHead[0] + " " + "asc";
57         }
58         
59         sr.Close();
60         fs.Close();
61         return dt;
62     }
63 }

找了好多只有这个好用 ================================================================

================================================================================================================================转自https://www.cnblogs.com/Clin/archive/2013/03/14/2959022.html===================

========================================================================================================================

posted @ 2018-05-31 17:29  葡萄老祖  阅读(1739)  评论(0编辑  收藏  举报