C# 将DataTable 导出 CSV

完整代码

 public static bool dataTableToCsv(DataTable table, string file)
        {
            try
            {
                string title = "";
                FileStream fs = new FileStream(file, FileMode.OpenOrCreate);
                //FileStream fs1 = File.Open(file, FileMode.Open, FileAccess.Read);

                StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);

                for (int i = 0; i < table.Columns.Count; i++)
                {
                    title += table.Columns[i].ColumnName + "\t"; //栏位:自动跳到下一单元格
                }
                title = title.Substring(0, title.Length - 1) + "\n";
                sw.Write(title);
                foreach (DataRow row in table.Rows)
                {
                    string line = "";
                    string strValue = "";
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        //bool containsNewLineDoubleQuote = row[i].ToString().Contains("\t"); // 检查直接字符
                        //if (containsNewLineDoubleQuote == true)
                        //{
                        //     MessageBox.Show(row[i].ToString());
                        //}

                        strValue = row[i].ToString().Trim();
                        // 使用正则表达式移除所有换行符 
                        strValue = System.Text.RegularExpressions.Regex.Replace(strValue, @"[\r\n]+", "  ");
                        strValue = System.Text.RegularExpressions.Regex.Replace(strValue, @"[\t]+", "  ");

                        line += strValue + "\t"; //内容:自动跳到下一单元格
                    }
                    //line = line.Substring(0, line.Length - 1) + "\n";
                    //sw.Write(line);
                    sw.WriteLine(line);
                }
                sw.Close();
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

调用方法

private void btnToExcel_BtnClick(object sender, EventArgs e)
{
            DataTable dt = this.dataGridView1.DataSource as DataTable;

            if (dt == null || dt.Rows.Count <= 0)
            {
                MessageBox.Show("没有要导出的数据,请查询后再试!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            // 设置默认文件名
            saveFileDialog.FileName = "安装工单导出-" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            saveFileDialog.Filter = "Excel2003 (*.xls)|*.xls|Excel (*.xlsx)|*.xlsx";

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string strFileName = saveFileDialog.FileName;
                // 处理文件路径
                string strFileName = @"d:\安装工单导出-" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                //bool bolResult=clsDataTableToCVS.dataTableToCsv(dt, @"d:\cccc.xls");
                bool bolResult = clsDataTableToCVS.dataTableToCsv(dt, strFileName);
  
                if (bolResult == true)
                {
                    MessageBox.Show("安装工单 导出成功!" , "消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("安装工单 导出失败!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
}

 

posted @ 2024-04-23 14:59  海乐学习  阅读(259)  评论(0编辑  收藏  举报