Search code examples
c#.netnpoixssf

Does NPOI support copying a worksheet and inserting it into the same workbook?


I'm new to using NPOI and the XSSF interfaces.

Does NPOI XSSF support copying a sheet and inserting it into the same workbook?

From reading, I see that through HSSF I can copy a sheet and insert it into a new workbook.

I know that Aspose.Cells supports this functionality. Is this functionality available through NPOI XSSF?


Solution

  • Yes, you can copy a sheet and insert it to the same workbook with the CopyTo method of an XSSFSheet. You need to make sure the copied sheet has a different name to avoid generating an exception.

    Note that this method what introduced in NPOI 2.4.0.

    Here's an example of copying the first sheet (at index 0) of a workbook:

    XSSFWorkbook workbook;
    
    using (FileStream fs = new FileStream(@"c:\temp\test.xlsx", FileMode.Open, FileAccess.Read))
    {
        workbook = new XSSFWorkbook(fs);
    }
    
    XSSFSheet sheet = workbook.GetSheetAt(0) as XSSFSheet;
    sheet.CopyTo(workbook, $"{sheet.SheetName}_copy", true, true);
    
    using (FileStream fs = new FileStream(@"c:\temp\test.xlsx", FileMode.Create, FileAccess.Write))
    {
        workbook.Write(fs);
    }