11

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).

Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
willowherb
  • 837
  • 1
  • 13
  • 21
  • Have you tried to follow the tutorial in the Apache website? It's not so hard!Write some code by yourself then ask! – Harry.Chen Apr 14 '13 at 11:38
  • I did try..but as mentioned in my question the API uses different classes to handle different types. See my comment below. – willowherb Apr 14 '13 at 11:51
  • Well,then I think you have to build your own interface to hide the underline implementation detail, the Abstract Factory Pattern for example. – Harry.Chen Apr 14 '13 at 12:01
  • @Harry.Chan seems I might end up..doing just that ... – willowherb Apr 14 '13 at 12:05

2 Answers2

22

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

Gagravarr
  • 47,320
  • 10
  • 111
  • 156
2

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.

Tarmo R
  • 1,123
  • 7
  • 15
  • A quick glance at Apache POI documentation shows, that both HSSF and XSSF seem to implement same interfaces - HSSFWorkbook and XSSFWorkbook for example both have a Workbook interface to work with. You just need to detect the type, instantiate the correct type and the rest of the code should be doable through the general interface. – Tarmo R Apr 14 '13 at 12:05
  • 1
    POI provides a class for detecting the type and building the correct object for you - `WorkbookFactory` - see my answer for details – Gagravarr Apr 14 '13 at 18:46