Monday, October 10, 2011

Create excel file report with multiple sheets using poi

Previously have done a program to generate and populate excel file on multiple sheets. Firstly download the poi framework jar files from their website http://poi.apache.org/.
Then using array of strings, populate the array according to where the location the cell is. Example below, first array is the row and second array is the column.

String[][] excelData = new String[2000][50];

excelData[0][0] = "Title";
excelData[0][1] = "Name";
excelData[0][2] = "Code";
excelData[0][3] = "Description";


excelData[1][0] = "title 1";
excelData[1][1] = "mike";
excelData[1][2] = "code 1";
excelData[1][3] = "Description 1";


Depending on the number of sheets to generate in the excel file, add the array of strings into an arraylist.

Then pass the list of string of array to the method below together with the file name of excel to generate.
The sheet name to generate is declared in variable sheetName.


private static void writeDataToExcelFile(String fileName,
List<String[][]> resList) {
HSSFWorkbook myWorkBook = new HSSFWorkbook();
String sheetName = "";
for (int i = 0; i < resList.size(); i++) {
sheetName = "Document-" + i;
HSSFSheet mySheet = myWorkBook.createSheet(sheetName);
HSSFRow myRow = null;
HSSFCell myCell = null;
String[][] excelData = resList.get(i);
for (int rowNum = 0; rowNum < excelData.length; rowNum++) {
myRow = mySheet.createRow(rowNum);
for (int cellNum = 0; cellNum < excelData[0].length; cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(excelData[rowNum][cellNum]);
}
}
}


try {
FileOutputStream out = new FileOutputStream(fileName + ".xls");
myWorkBook.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}


myWorkBook = null;

}

1 comment:

  1. You can create excel file with multiple sheets by using Aspose.Cells for Java Library. You can also find many useful code examples on the documentation page of this library.

    ReplyDelete