excel export using EPPlus

本文介绍如何使用EPPlus库将DataTable数据导出到Excel文件中,并提供了详细的代码示例。通过设置单元格样式、自适应列宽以及定义工作表的头部样式等操作,实现了美观的数据展示。

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

Have a look at ExeclPackagePlus http://epplus.codeplex.com

It's great for these kinds of scenarios.

 private void DumpExcel(DataTable tbl)
    {
        try{
         //   OfficeOpenXml.ExcelPackage
        using (ExcelPackage pck = new ExcelPackage())
        {
            //Create the worksheet
            ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Mailing List");

            //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
            ws.Cells["A2"].LoadFromDataTable(tbl, false);

            //Header Titles
            ws.Cells["A1"].Value = "Employee Name";
            ws.Cells["B1"].Value = "Email Address";
            ws.Cells["C1"].Value = "Phone";
            ws.Cells["D1"].Value = "Business Unit";
            ws.Cells["E1"].Value = "Site";

            ws.Cells["A1"].AutoFitColumns();

            //Format the header for column 1-3
            using (ExcelRange rng = ws.Cells["A1:E1"])            {
              
                rng.Style.Font.Bold = true;
                //Set Pattern for the background to Solid
                rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
                //Set color to dark blue
                rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(79, 129, 189));
                rng.Style.Font.Color.SetColor(System.Drawing.Color.White);
            }


            //Write it back to the client          

            Response.Clear();
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=MailingList.xlsx");
            Response.BinaryWrite(pck.GetAsByteArray());           
        }
        }
        catch (Exception ex) 
        {
    //log error
        }
           Response.End();
        }

 

转载于:https://www.cnblogs.com/happy-Chen/p/3622782.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值