0
votes

I have a Java method writeToExcel(String sheetName, Map), which creates a new sheet with name 'sheetName' in a new excel file and write the map data into it . When I call the method with different sheetName arguments more than once, existing sheet gets replaced by the last called one. I want to create new sheets in the same excel file each time whenever the method is called with different sheetName argument, without losing existing sheets. Here is my code.

public static void writeToExcel(String fileName,Map<Integer,String[]> excelData){
    String filePath="/Data/excel.xlsx";
    XSSFWorkbook workbook=new XSSFWorkbook();
    XSSFSheet sheet=workbook.createSheet(fileName);
    Set<Integer> keySet=excelData.keySet();
    int passedCount=0;
    int failedCount=0;
    int rowNo=0;
    int cellNo=0;
    Row row;
    Cell cell;
    try{
        File file=new File(filePath);
        FileOutputStream output=new FileOutputStream(file);
        for(Integer key:keySet){
            row=sheet.createRow(rowNo++);
            String[] dataToWrite=excelData.get(key);
            cellNo=0;
            for(String str:dataToWrite){
                cell=row.createCell(cellNo++);
                cell.setCellValue(str);
            }
        }
        workbook.write(output);
        output.close();
        workbook.close();
    }
    catch(FileNotFoundException e){
        e.printStackTrace();
    }
    catch(IOException e){
        e.printStackTrace();
    }
}
2
Post provide MCVE. Be sure to copy-paste your code to a new project and make sure it compiles and runs before posting it here. - user1803551

2 Answers

1
votes

Seems like you're always creating a new workbook in the second line of the method. So it is not the sheet that is replaced but the entire workbook. Better use

XSSFWorkbook workbook=new XSSFWorkbook(new File(filePath));

That should do the trick.

-1
votes

XSSFWorkbook workbook=new XSSFWorkbook(new File(filePath)); => XSSFWorkbook workbook=new XSSFWorkbook(filePath); as no suit constructor for XSSFWorkbook workbook=new XSSFWorkbook(new File(filePath))