Export datatable to excel using EPPlus with additional data

做~自己de王妃 提交于 2020-01-06 20:26:16

问题


I have a requirement where i have to generate the excel as below image

i am using EPPlus dll and i am able to export only datatable to excel directly with below c# code.

     using (var package = new ExcelPackage(Template))
                    {
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Product_Reports");
            worksheet.Cells["A1"].LoadFromDataTable(dt, true, TableStyles.Medium1);          
            worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();

    ... remainig code

How to i add the heading "Product Statistics" and other data like "Total", "Sold Out" etc as shown in the image ??


回答1:


The examples on eppplus's site should show you how to do all of this but here is a start:

[TestMethod]
public void Table_Export_Test()
{
    //http://stackoverflow.com/questions/31042901/export-datatable-to-excel-using-epplus-with-additional-data
    //Throw in some data
    var dtdata = new DataTable("tblData");
    dtdata.Columns.Add(new DataColumn("Order no.", typeof (string)));
    dtdata.Columns.Add(new DataColumn("Product name", typeof (int)));
    dtdata.Columns.Add(new DataColumn("Name", typeof (int)));

    for (var i = 0; i < 20; i++)
    {
        var row = dtdata.NewRow();
        row[0] = i;
        row[1] = i*10;
        row[2] = i*100;
        dtdata.Rows.Add(row);
    }


    var existingFile = new FileInfo(@"c:\temp\temp.xlsx");
    if (existingFile.Exists)
        existingFile.Delete();

    using (var package = new ExcelPackage(existingFile))
    {
        var ws = package.Workbook.Worksheets.Add("Sheet1");
        ws.Cells["A1"].Value = "Product Statistics";
        ws.Cells[1, 1, 1, 6].Merge = true;

        ws.Cells[3, 3].Value = "Total";
        ws.Cells[3, 4].Value = "200";

        ws.Cells[4, 3].Value = "Sold out";
        ws.Cells[4, 4].Value = "50";

        ws.Cells[1, 1, 1, 6].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        ws.Cells[3, 3, 6, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
        ws.Cells[3, 4, 6, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;

        ws.Cells[6, 1].LoadFromDataTable(dtdata, true);

        ws.Column(1).Width = 13;
        ws.Column(2).Width = 13;
        ws.Column(3).Width = 13;
        ws.Column(4).Width = 13;

        package.Save();
    }

}


来源:https://stackoverflow.com/questions/31042901/export-datatable-to-excel-using-epplus-with-additional-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!