![](/img/trans.png)
[英]Excel file gets corrupted after overwrite in Android with apache poi
[英]Excel file gets corrupted after launching an executable jar
我有一个 Eclipse 项目,其中包含以下使用 Apache POI 的代码。
public static void main(String[] args){
try{
XSSFWorkbook sourceWorkbook = new XSSFWorkbook("input.xlsx");
XSSFSheet sheet = sourceWorkbook.getSheetAt(0);
// do stuff
sourceWorkbook.close();
} catch (IOException e){
e.printStackTrace();
}
}
当我从 Eclipse 启动它时,它工作正常。 由于我创建了可执行文件 jar,当我使用它时,Excel 输入文件从 9 增加到 1 kB,并且不再打开。
[编辑:因为有人问我:
我该如何解决?
您可以尝试以下选项:
FileInputStream
到工作簿路径try
-with-resources 语句中执行此操作try
块内的工作簿也许像这样:
public static void main(String[] args) {
String wbPath = "input.xlsx";
// use an auto-closable resource stream
try (FileInputStream fis = new FileInputStream(wbPath)) {
// then use that in order to open the workbook
Workbook workbook = new XSSFWorkbook(fis);
// then open the sheet
Sheet sheet = workbook.getSheetAt(0);
// and do stuff…
// Having done stuff, close the workbook explicitly
workbook.close();
// and let the try with resources close the input stream
} catch (FileNotFoundException e) {
// do proper exception handling here
throw new RuntimeException("file " + wbPath + " seems not to exist");
} catch (IOException e) {
// do proper exception handling here, too
throw new RuntimeException("error during read or write operation");
}
}
RuntimeException
仅用于使代码正常工作,而不仅仅是在那里打印堆栈跟踪。 正如评论所说,您可能想在catch
块中做一些更好的事情。
作为new XSSFWorkbook(fis)
的替代方案,您可以使用WorkbookFactory
来create(fis)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.