Tuesday 14 September 2010

How to use xls ( Excel ) files in Java

How to use xls (Excel) files in Java

First, you need the POI library. You can download it here.


To work with a xls File with Java is very easy. Simply, you have to fix in Rows and Cells.













I show you a part of source code, it's more easy to understand.

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

Workbook wb = new XSSFWorkbook();
FileOutputStream fos = new FileOutputStream("C:\\sample.xlsx");
Sheet sh = wb.createSheet("newSheet1");
sh.createRow(0);

sh.getRow(0).createCell(0).setCellValue("Hours");
sh.getRow(0).createCell(1).setCellValue("Sunday");
sh.getRow(0).createCell(2).setCellValue("Monday");
sh.getRow(0).createCell(3).setCellValue("Tuesday");
sh.getRow(0).createCell(4).setCellValue("Wednesday");
sh.getRow(0).createCell(5).setCellValue("Thursday");
sh.getRow(0).createCell(6).setCellValue("Friday");
sh.getRow(0).createCell(7).setCellValue("Saturday");





for(int k = 1; k<25;k++){
sh.createRow(k);
sh.getRow(k).createCell(0).setCellValue(k-1);
}

for (int i = 0; i <>
for(int j = 0; j<24;j++){
sh.getRow(j+1).createCell(i+1).setCellValue("Row "+j+" Cell "+i);
}
}

To finish correctly you need add this:

wb.write(fos);
fos.close();




















Now, the file already contents the data.

See you.

0 comments: