C#直接循环写入stream,导出到excel(1)

本文介绍了一种使用C#将DataTable中的数据导出到CSV文件的方法。此方法首先检查系统是否安装了Excel,并通过StreamWriter实现CSV文件的创建与写入,包括表头和数据行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


public static void ExportCSV(System.Data.DataTable table, string path)
        {
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                MessageBox.Show("导出表格失败,请检查电脑是否已安装Excel。", "提示");

             }
            StreamWriter writer;
            bool comma = false;
            int columns = table.Columns.Count;
            using (writer = new StreamWriter(path, false, Encoding.UTF8)) ///设置表格编码是UTF8
            {
                foreach (DataColumn col in table.Columns)
                {
                    if (!comma)
                        comma = true;
                    else
                        writer.Write(',');
                    writer.Write(col.ColumnName);
                }
                writer.WriteLine();
                foreach (DataRow row in table.Rows)
                {
                    comma = false;
                    for (int c = 0; c < columns; c++)
                    {
                        if (!comma) comma = true;
                        else writer.Write(',');
                        writer.Write(row[c].ToString());
                    }
                    writer.WriteLine();
                }
            }
        }


---------------------------------------------调用------------
DataTable dt = new DataTable();
            dt = ds.Tables[1];
           
            DateTime now = DateTime.Now;
            string sFileName = now.Year.ToString().PadLeft(2) + now.Month.ToString().PadLeft(2, '0') + now.Day.ToString().PadLeft(2, '0') + "-" + now.Hour.ToString().PadLeft(2, '0') + now.Minute.ToString().PadLeft(2, '0') + now.Second.ToString().PadLeft(2, '0');

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "导出数据到";
            saveFileDialog.FileName = sFileName + ".csv";
            saveFileDialog.ShowDialog();
           
            ExcelHelper.ExportCSV(dt, saveFileDialog.FileName);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值