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
It's best if you worked with DataSet
s and/or DataTable
s. 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();
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();
}
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();
}