How to add new sheets to existing excel workbook using apache POI?

前端 未结 5 531
心在旅途
心在旅途 2020-12-15 12:48

I am trying to write List data into multiple excel sheet in one work book. like for first list, the code will create new workbook and create new sheet for list[1], for secon

5条回答
  •  一向
    一向 (楼主)
    2020-12-15 13:19

    If file does not exist then this code creates new file and also creates sample sheet1 but if file exists then it adds new sheet to existing excel file.

        HSSFWorkbook workbook = null;
        File file = new File(context.getExternalFilesDir(null), "Sample.xls");
        FileOutputStream fileOut = new FileOutputStream(file);
    
        if (file.exists()) {
            try {
                workbook = (HSSFWorkbook)WorkbookFactory.create(file);
            } catch (InvalidFormatException e) {
                e.printStackTrace();
            }
            HSSFSheet sheet = workbook.createSheet("Sample sheet2");
        }
        else{
            workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("Sample sheet1");
        }
        workbook.write(fileOut);
        fileOut.close();
    

提交回复
热议问题