Writing an Excel file in EPPlus

前端 未结 3 1741
青春惊慌失措
青春惊慌失措 2021-01-31 17:45

I have been stuck on this for days and despite all of the help out there, none of these solutions have been working for me. What I want to do is create an excel file using the E

相关标签:
3条回答
  • 2021-01-31 18:14

    It's best if you worked with DataSets and/or DataTables. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:

    ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);

    .. which will produce a beautiful excelsheet with a nice table!

    Now to serve your file, assuming you have an ExcelPackage object as in your code above called pck..

    Response.Clear();
    
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);
    
    Response.BinaryWrite(pck.GetAsByteArray());
    Response.End();
    
    0 讨论(0)
  • 2021-01-31 18:15

    If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection.

    using (ExcelPackage package = new ExcelPackage(file))
    {
        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");
    
        worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);
    
        package.Save();
    }
    
    0 讨论(0)
  • 2021-01-31 18:34

    Have you looked at the samples provided with EPPlus?

    This one shows you how to create a file http://epplus.codeplex.com/wikipage?title=ContentSheetExample

    This one shows you how to use it to stream back a file http://epplus.codeplex.com/wikipage?title=WebapplicationExample

    This is how we use the package to generate a file.

    var newFile = new FileInfo(ExportFileName);
    using (ExcelPackage xlPackage = new ExcelPackage(newFile))
    {                       
        // do work here                            
        xlPackage.Save();
    }
    
    0 讨论(0)
提交回复
热议问题