如何使用 POI SS 打开 .xlsx 文件? [英] How to open .xlsx files with POI SS?
本文介绍了如何使用 POI SS 打开 .xlsx 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用此代码(取自 http://poi.apache.org/spreadsheet/quick-guide.html#ReadWriteWorkbook):
I am trying to open .xlsx files with POI SS with this code (taken from http://poi.apache.org/spreadsheet/quick-guide.html#ReadWriteWorkbook):
InputStream inp = new FileInputStream("workbook.xls");
//InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
if (cell == null)
cell = row.createCell(3);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("a test");
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
我收到此错误消息:
Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/DocumentException
我将 xbean.jar 添加到我的库和运行时库中.
I add the xbean.jar to my library and to my run-time libraries.
如何解决此异常?
谢谢!
推荐答案
第一:修复异常
有两种解决方案:
First: Fix the Exception
There are two solutions:
- 正如 Gagravarr 已经提到的:您需要 dom4j 来修复您的异常.
- 正如 Jon 已经提到的:你必须更新你的依赖项,所以你不再需要 dom4j.
如果您使用 Maven,您可以添加必要的依赖项:(也许检查更新版本:Maven 存储库:org.apache.poi)
If you're using Maven, you can add the necessary dependencies with: (Maybe check for newer versions at: Maven Repository: org.apache.poi)
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
然后:打开文件
如果您修复了异常,您可以使用以下代码打开您的 file.xlsx
文件:
String path = "Relative/Path/To/Your/File/file.xlsx";
File file = new File(path);
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
// Use your sheet ...
更多提示
- 与 Gagravarr 一样,我也建议使用文件而不是文件输入流.
- 如果你想打开某个工作表,你可以使用
workbook.getSheet(String name);
- 如果根据您的项目不知道文件的相对路径,您可以使用
System.out.println("Relative path:" + System.getProperty("user.dir"));
问候,winklerrr
Regards, winklerrr
这篇关于如何使用 POI SS 打开 .xlsx 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文