使用Apache POI从java中的xls和xlsx excel文件读写

时间:2022-04-19 20:20:50

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

我正在编写一个程序,该程序需要从excel文件中读写,而不考虑格式(xls或xlsx)。

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

我知道Apache POI,但是它似乎有不同的类来处理xls文件(HSSF)和xlsx(XSSF)文件。

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

任何人都知道我是如何实现我的目标的。(也欢迎使用POI以外的API)。

2 个解决方案

#1


23  

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

您可以读取、编写、编辑等现有文件,包括.xls和.xlsx,只要使用公共接口,就可以使用完全相同的代码

#2


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.

为什么不从扩展名中检测文件类型并使用适当的Apache POI类进行处理呢?我怀疑对于你的情况是否有一种绝对通用的开箱即用的解决方案。

#1


23  

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

您可以读取、编写、编辑等现有文件,包括.xls和.xlsx,只要使用公共接口,就可以使用完全相同的代码

#2


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.

为什么不从扩展名中检测文件类型并使用适当的Apache POI类进行处理呢?我怀疑对于你的情况是否有一种绝对通用的开箱即用的解决方案。