Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading and writing from xls and xlsx excel file in java using Apache POI

I am writing a program which needs to read and write from excel files, irrespective of the format(xls or xlsx).

I am aware of the Apache POI, but it seems it has different classes to handle xls file(HSSF) and xlsx(XSSF) files.

Anyone aware of how I might achieve what I am trying to do here. (Ideas for using an API other than POI are also welcome).

like image 424
Shiva Avatar asked Apr 14 '13 11:04

Shiva


2 Answers

It's very easy, just use the common SpreadSheet interfaces

Your code would look something like:

 Workbook wb = WorkbookFactory.create(new File("myFile.xls")); // Or .xlsx
 Sheet s = wb.getSheet(0);
 Row r1 = s.getRow(0);
 r1.createCell(4).setCellValue(4.5);
 r1.createCell(5).setCellValue("Hello");

 FileOutputStream out = new FileOutputStream("newFile.xls"); // Or .xlsx
 wb.write(out);
 out.close();

You can read, write, edit etc an existing file, both .xls and .xlsx, with exactly the same code as long as you use the common interfaces

like image 131
Gagravarr Avatar answered Oct 21 '22 06:10

Gagravarr


Why not detect the file type from extension and use the appropriate Apache POI class for processing? I doubt there's an absolutely universal out-of-the-box solution for your situation.

like image 41
Tarmo R Avatar answered Oct 21 '22 06:10

Tarmo R