Skip to content
Advertisement

How to copy excel sheet to the same worbook?

I’m trying to copy an existing excel sheet to the same workbook(it contains 3 sheets ) in java using Apache poi .

Here is what i did :

    FileInputStream file = new FileInputStream(new File("work.xlsx"));
    
    XSSFWorkbook workbook = new XSSFWorkbook(file);
    
    XSSFSheet sheet_copy =   workbook.cloneSheet(0);
    
    int num = workbook.getSheetIndex(sheet_copy);
    
    workbook.setSheetName(num, "copy_file");
    

after running this code, the workbook contains always 3 sheets , the “copy_file” is not created, i’m not getting any errors or exceptions .

any idea ?

Advertisement

Answer

You need to open an output stream and write to the workbook. Make sure to close the workbook and the output stream after this write operation.

Demo:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Main {
    public static void main(String[] args) throws IOException {
        FileInputStream file = new FileInputStream(new File("work.xlsx"));
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet sheet_copy = workbook.cloneSheet(0);
        int num = workbook.getSheetIndex(sheet_copy);
        workbook.setSheetName(num, "copy_file");
        file.close();

        FileOutputStream outputStream = new FileOutputStream("work.xlsx");
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();
    }
}
Advertisement