Java Apache POI,同时使用 XSSF 和 HSSF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4266888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Apache POI, using both XSSF and HSSF
提问by Tim Tuckle
I have a problem with Apache POI project.
我有 Apache POI 项目的问题。
I failed to use XSSF
and HSSF
in the "Same Java Class". Which jar should I download or which artifact should I get add into maven?
我未能在“相同的 Java 类”中使用XSSF
和。我应该下载哪个 jar 或者我应该将哪个工件添加到 maven 中?HSSF
I want to handle both xls
and xlsx
files at the same time. When I get excel version error, I will change the XSSF to HSSFor HSSF to XSSF.
我想同时处理xls
和xlsx
文件。当我收到 excel 版本错误时,我会将XSSF更改为 HSSF或HSSF 为 XSSF。
How can I do this?
我怎样才能做到这一点?
采纳答案by evilReiko
Instead of doing that, try using the new release of Apache POI 3.7, it has SS package which handles both HSSF and XSSF without worrying about type
与其这样做,不如尝试使用 Apache POI 3.7 的新版本,它有一个 SS 包,可以处理 HSSF 和 XSSF 而无需担心类型
Details here: http://poi.apache.org/spreadsheet/index.html
回答by XenoRo
Aside from the "standard" SS package solution, you can also simply use an if statement
to correctly load the right workbook format
into an Workbook interface
object, like so:
除了“标准”SS 包解决方案,您还可以简单地使用 anif statement
将权限正确加载workbook format
到Workbook interface
对象中,如下所示:
Workbook workbook; //<-Interface, accepts both HSSF and XSSF.
File file = new File("YourExcelFile.xlsx");
if (FileUtils.getFileExt(file).equalsIgnoreCase("xls")) {
workbook = new HSSFWorkbook(new FileInputStream(file));
} else if (FileUtils.getFileExt(file).equalsIgnoreCase("xlsx")) {
workbook = new XSSFWorkbook(new FileInputStream(file));
} else {
throw new IllegalArgumentException("Received file does not have a standard excel extension.");
}
回答by vingin
Use the factory instead which handles both xssf and hssf
改用处理 xssf 和 hssf 的工厂
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
Workbook wb = WorkbookFactory.create(new File("file"))
回答by Hamid Raza Abdul
This worked for me:
这对我有用:
filePath = "C:\Users\user1\workspace\myproject\Excel.xlsx"
String extension = FilenameUtils.getExtension(filePath);
System.out.println(extension);