C#输入Datatable写Csv文件

using System.IO;
using System.Data;
using System.Text;


        public void DataTableToWriteCsvFile(System.Data.DataTable data)
        {
            const int BufferSize = 4096;
            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.Title = "Csv";
            fileDialog.Filter = "CsvFile(*.csv)|*.csv";
            DialogResult dialogResult = fileDialog.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                string str = fileDialog.FileName;
                using (FileStream fs = new FileStream(str, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (BufferedStream bs = new BufferedStream(fs, BufferSize))
                    {
                        using (StreamWriter sw = new StreamWriter(bs, Encoding.Default))
                        {
                            StringBuilder data_str = new StringBuilder();
                            for (int k = 0; k < data.Columns.Count; k++)
                            {
                                if (k == data.Columns.Count - 1)
                                {
                                    data_str.Append("\"" + data.Columns[k].ColumnName.ToString() + "\"");
                                }
                                else
                                {
                                    data_str.Append("\"" + data.Columns[k].ColumnName.ToString() + "\"" + ",");
                                }
                            }
                            sw.Write(data_str + "\r\n");
                            data_str.Clear();
                            for (int i = 0; i < data.Rows.Count; i++)
                            {
                                for (int j = 0; j < data.Columns.Count; j++)
                                {
                                    if (j == data.Columns.Count - 1)
                                    {
                                        data_str.Append("\"" + data.Rows[i][j].ToString().Trim() + "\"");
                                    }
                                    else
                                    {
                                        data_str.Append("\"" + data.Rows[i][j].ToString().Trim() + "\"" + ",");
                                    }
                                }
                                sw.Write(data_str + "\r\n");
                                data_str.Clear();
                            }
                            data_str.Clear();
                        }
                    }
                }
                MessageBox.Show("The csv-file  saved successfully.");
            }
        }

 

C#输入Datatable写Csv文件

上一篇:NET Core创建Windows服务


下一篇:视觉光盘,只有我可以贴全世界唯一,Windows上*的DOCKER客户端数字, 夜晚点击一个都没有,值班的小编辛苦了