0

I am trying to create sheets in a new workbook using apache poi.

However, I want the sheets created to be the name of studies in an arraylist.

I don't know how many studies there are, or what they are beforehand. I am having trouble setting it up.

public static void addSheets() {
XSSFWorkbook finalizing = new XSSFWorkbook();
    for (int i = 0; i < studies.size(); i++) {
        finalizing.createSheet(studies.get(i));
    }

    makeWorkBook(finalizing);
}

I have also tried

XSSFSheet firstSheet = finalizing.createSheet(studies.get(i));

instead of the finalizing.createSheet

But neither work.

I was hoping to get advice from anyone?

  • 5
    What does _neither work_ mean? Does the code compile? Is there an exception when running? – Andrew S Oct 30 '17 at 13:10
  • First of all, you should not write code for creating a Workbook in a method named addSheets(). – Yash Oct 31 '17 at 12:01

1 Answers1

0

This code is working for me:

public void createExcel(String filename){
    List<String> sheetNames = new ArrayList<String>();
    sheetNames.add("S1");
    sheetNames.add("S2");
    sheetNames.add("S3");
    try{
        File file = new File(filename);
        if(!file.exists()){
            file.createNewFile();
        }
        XSSFWorkbook workbook=new XSSFWorkbook();
        for(String sheetName: sheetNames){
            workbook.createSheet(sheetName);
        }
        FileOutputStream fileOut =  new FileOutputStream(filename);
        workbook.write(fileOut);
        fileOut.close();

    } catch ( Exception ex ) {
        System.out.println("Exception creating the excel file: " + ex.getMessage());
    }
}

Please, could you add what you are doing in your method makeWorkBook. It seems that probably there is your problem.

Also, be sure that you are adding a valid sheet name.

  • The name must be unique within a single workbook.
  • A worksheet name cannot exceed 31 characters.
  • You can use all alphanumeric characters but not the following special characters: \ , / , * , ? , : , [ , ].
ervidio
  • 571
  • 5
  • 12