Microsoft Excel is a perfect tool for working with data-intensive computations and calculations. People use it in their routine work to carry out complex calculations such as mathematical formula implementation, statistical analysis and many more. Data in an Excel worksheet may often need to be replicated in another worksheet in the same workbook for further operations and modifications. This can be achieved easily by using the COPY operation in Excel. As a .NET application developer, you can use the NPOI API for .NET to copy an Excel worksheet using C# or VB.NET as explained in this article.
In this article, we’ll show how to copy a worksheet in an Excel file with NPOI using C#/VB.NET. But first, let us have a look at how to copy a worksheet using Microsoft Excel.
Copy Worksheet using Microsoft Excel
Excel lets you create copy of a worksheet in a workbook that you can further work with by modifying its data. You can do this as explained in the following steps.
Steps to Copy Excel Worksheet
Press CTRL and drag the worksheet tab to the tab location you want.
OR
- Right click on the worksheet tab and select Move or Copy.
- Select the Create a copy checkbox.
- Under** Before sheet**, select where you want to place the copy.
- Select OK.
Copy Excel Worksheet using NPOI in C#
Now that we have seen how to copy a worksheet using Microsoft Excel, we can move towards doing the same using NPOI API for .NET in C#. But before that, you need to install NPOI in your .NET project to get started. You can learn about this in our detailed instructions guide for Installing NPOI for .NET.
Copy Excel Worksheet using C#
Now that your development environment is ready for working with NPOI API in C#, you can create a console-based project and add the following lines of code.
//Load workbook
IWorkbook workbook = new XSSFWorkbook(new FileStream("SampleFile.xlsx", FileMode.Open));
//Get the first worksheet
ISheet sheet = workbook.GetSheetAt(0);
//Copy to a new sheet
sheet.CopySheet("copied sheet", true);
//Save the file
FileStream file = File.Create("CopiedSampleFile.xlsx");
workbook.Write(file, false);
file.Close();
Conclusion
In this article, we explored how to copy an Excel worksheet using NPOI for .NET API. The sample code is written in C#, but can easily be converted to VB.NET. For more code samples on working with Excel spreadsheets using NPOI API for .NET, stay tuned to our blog.