Question

I'm using EPPlus to export an excel. I have done some functions to get a "ExcelWorksheet". I would like join all of them in one excel(one per tab) using it but I don't know how can I do it.

here is the main function:

public ActionResult ExportReports(string sheetName)
{
    try
    {
        var req = GetRequest();
        var fileDownloadName = "OnlineReport.xlsx";
        var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        var package = new ExcelPackage();
        var ws1 = AnalysisByAirCarrier(package, req);
        var ws2 = Summary(package, req);

        var fileStream = new MemoryStream();
        package.SaveAs(fileStream);
        fileStream.Position = 0;
        var fsr = new FileStreamResult(fileStream, contentType);
        fsr.FileDownloadName = fileDownloadName;

        return fsr;
    }
    catch (Exception ex)
    {
        _logger.Error("Error ExportReports", ex);
    }
}

I would like join ws1 and ws2 in the same file in different tabs.

note: ws1 and ws2 are ExcelWorksheet objects

any idea??

Thanks.

Was it helpful?

Solution

You should be able to add a copy of a worksheet to a workbook as a tab:

using(var package = new ExcelPackage())
{
    package.Workbook.Worksheets.Add("First worksheet 1", ws1);
    package.Workbook.Worksheets.Add("First worksheet 2", ws2);
    // Do something with the package
}

I'm not sure what you're doing in AnalysisByAirCarrier and Summary though.

I haven't tested it, but adding blank worksheets and operating on them works just as expected for me (it creates multiple tabs which I can fill with content)

[edit]: Updating "First worksheet" comment

OTHER TIPS

var groupedSheetList = UserData.GroupBy(u => u.date).Select(grp => grp.ToList 
()).ToList();
using (var package = new ExcelPackage ()) {
foreach (var item in groupedSheetList){
var workSheet = package.Workbook.Worksheets.Add (item[0].date);}}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top