如何使用 POI SS 打开 .xlsx 文件?

Yon*_*oni 2 java excel apache-poi

我正在尝试使用以下代码使用 POI SS 打开 .xlsx 文件(取自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();
Run Code Online (Sandbox Code Playgroud)

我收到此错误消息:

Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/DocumentException
Run Code Online (Sandbox Code Playgroud)

我将 xbean.jar 添加到我的库和运行时库中。

我该如何解决这个异常?

谢谢 !

win*_*rrr 5

第一:修复异常

有两种解决方案:

  1. 正如 Gagravarr 已经提到的:你需要 dom4j 来修复你的异常。
  2. 正如 Jon 已经提到的:您必须更新依赖项,因此您不再需要 dom4j。

如果您使用 Maven,则可以添加必要的依赖项:(也许可以在以下位置检查较新的版本:Maven 存储库: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>
Run Code Online (Sandbox Code Playgroud)

然后:打开文件

如果您已修复该异常,则可以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 ...
Run Code Online (Sandbox Code Playgroud)

更多提示

  • 与 Gagravarr 一样,我也建议使用文件而不是文件输入流。
  • 如果你想打开某个工作表,你可以使用workbook.getSheet(String name);
  • 如果您不知道根据您的项目的文件的相对路径,您可以轻松地检查它System.out.println("Relative path: " + System.getProperty("user.dir"));

问候,温克勒