Search code examples
c#excelepplus

EPPlus multiple tabs c#


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.


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