Search code examples
c#excelepplus

How to copy an excel worksheet from a file to another using EPPlus for .NET


Given the following scenario:

  • I have a source.xlsx file with multiple worksheets (worksheet1, worksheet2, workshToCopy, etc) and I generate the destination.xlsx based on another .xlsx template file that has different worksheets than the source.xlsx. I want to add a worksheet from the source file to the destination file.

For now I was able to add an empty worksheet to my destination file like this:

if (FileExists(outputFile) && FileExists(inputFile))
{
  var inputPackage = new ExcelPackage(inputFile);
  var outputPackage = new ExcelPackage(outputFile);

  var summaryInputWorksheet = inputPackage.Workbook.Worksheets[ExcelSummaryHelper.SummaryWorksheet];
  outputPackage.Workbook.Worksheets.Add(summaryInputWorksheet.Name);
  outputPackage.Workbook.Worksheets.MoveToEnd(summaryInputWorksheet.Name);
  outputPackage.Save();
}

What's the best approach to copy the content of workshToCopy from source.xlsx to destination.xlsx's new worksheet using the EPPlus library ?


Solution

  • Solved.

    There's an overload for the Add method on the ExcelWorksheets class that looks like this:

    ExcelWorksheets.Add(string Name, ExcelWorksheet Copy)
    

    Can't believe I haven't seen it.