C# web 把dataSet数据导出为Excel文件

引入命名空间:

using System.Data;
using Microsoft.Office.Interop.Excel;

添加com引用:

Microsoft.Office.Interop.Excel.dll

OFFICE.DLL

C#:

public void doReports(System.Data.DataSet ds, string strExcelFileName)
        {
            strExcelFileName = "D:/"+ strExcelFileName + ".xls";
        
            bool fileSaved = false;

            Application xlApp = new Application();

            if (xlApp == null)
            {
                return;
            }

            Workbooks workbooks = xlApp.Workbooks;
            Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            Worksheet worksheet = (Worksheet)workbook.Worksheets[1];//取得sheet1
            //写入字段
            for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
            {
                worksheet.Cells[1, i + 1] = ds.Tables[0].Columns[i].ColumnName;
            }
            //写入数值

            for (int r = 0; r < ds.Tables[0].Rows.Count; r++)
            {
                for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                {
                    worksheet.Cells[r + 2, i + 1] = ds.Tables[0].Rows[r][i];
                }
      
            }
            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。

            if (strExcelFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(strExcelFileName);//保存创建文件
                    fileSaved = true;
                }
                catch (Exception ex)
                {
                    fileSaved = false;
                }
            }
            else
            {
                fileSaved = false;
            }
            xlApp.Quit();
            GC.Collect();//强行销毁

 

          //导出成功就打开文件
            if (fileSaved && System.IO.File.Exists(strExcelFileName))

                System.Diagnostics.Process.Start(strExcelFileName); //打开EXCEL
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值