Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 976
Ovy.Istrate Avatar asked Mar 14 '18 15:03

Ovy.Istrate


People also ask

How do I copy a worksheet from one workbook to another in C#?

The following are the steps to perform this operation. Create an object of the Workbook class and load the source Excel file. Create another object of the Workbook class and load the destination Excel file. Copy worksheet from source to destination workbook using destinationWorkbook.

Does EPPlus work with XLS?

EPPlus does not work with the XLS format. Only XLSX. You'll need to find a new library.

What is EPPlus C#?

EPPlus is a very helpful open-source 3rd party DLL for writing data to excel. EPPlus supports multiple properties of spreadsheets like cell ranges, cell styling, charts, pictures, shapes, comments, tables, protection, encryption, pivot tables, data validation, conditional formatting, formula calculation, etc.


2 Answers

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.

like image 50
Ovy.Istrate Avatar answered Nov 14 '22 23:11

Ovy.Istrate


Couldn't you just clone the existing one?

ExcelWorksheets clonedWorksheet = currentExcelWorksheet.Clone();
like image 31
Alex Avatar answered Nov 14 '22 21:11

Alex