本文介绍了如何用POI SS打开.xlsx文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图用这个代码打开带有POI SS的.xlsx文件(取自):
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.
我如何解决这个异常?
谢谢!
推荐答案
修复异常
有两种解决方案:
Fix the exception
There are two solutions:
- 由于Gagravarr已经提到:您需要dom4j来修复您的异常。
- Jon已经提到:你必须更新你的依赖关系,所以你不再需要dom4j了。
如果您使用Maven,则可以使用以下内容添加必要的依赖关系:(也可以在以下位置检查较新的版本:)
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>
打开.xlsx
修改了例外,您可以使用以下代码打开您的 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));
- Like Gagravarr, I also recommend to use a file instead of a file input stream.
- If you want to open a certain sheet you can use
workbook.getSheet(String name);
- If you don't know the relative path to your file according to your project, you can easily check it with
System.out.println("Relative path: " + System.getProperty("user.dir"));
Further tips
问候,winklerrr
Regards, winklerrr
这篇关于如何用POI SS打开.xlsx文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!