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.");
            }
        }

猜你喜欢

转载自www.cnblogs.com/codefish7/p/12323835.html