简体   繁体   English

使用Apache POI打开xls和xlsx

[英]Open xls and xlsx with Apache POI

I want to open my excel file with Apache POI. 我想用Apache POI打开我的Excel文件。

I don't know if a file is xls or xlsx. 我不知道文件是xls还是xlsx。 I have only something like this: 我只有这样的东西:

InputStream myExcelFile = new ByteArrayInputStream(file.getData());

This way I can open xls file: 这样我可以打开xls文件:

HSSFWorkbook hsf = new HSSFWorkbook(myxls);

And this way I can open xlsx file: 这样,我可以打开xlsx文件:

XSSFWorkbook xsf = new XSSFWorkbook(myxls);

How can I open both types of files if I don't know format? 如果我不知道格式,该如何打开这两种文件?

Workbook wb = WorkbookFactory.create(myExcelFile);
if (wb instanceof HSSFWorkbook) {
    // do whatever
} else if (wb instanceof SXSSFWorkbook) {
    // do whatever
} else if (wb instanceof XSSFWorkbook) {
    // do whatever
}

The aforementioned approach will work. 前述方法将起作用。

But incase you are dealing with large files, there is a possibility that you will get File as ByteArayInputStream . 但是,如果您要处理的是大文件,则有可能将File作为ByteArayInputStream获得。 In this case, the bellow approach shall work. 在这种情况下,应采用波纹管方法。

ByteArayInputStream bais = new ByteArrayInputStream(file.getData());

if(bais != null && POIFSFileSystem.hasPOIFSHeader(bais)) {
    System.out.println(".xls extention excel file");
    //do whatever
}
else if(bais != null && POIXMLDocument.hasOOXMLHeader(bais)) {
    System.out.println(".xlsx extention excel file");
    //do whatever
}
else {
    //wrong file format. throw exception.
}

This will do the work: 这将完成工作:

Workbook wb = WorkbookFactory.create(myExcelFile);

Then you can check the exact type created by the factory: 然后,您可以检查工厂创建的确切类型:

if (wb instanceof HSSFWorkbook) {
    // do whatever
} else if (wb instanceof SXSSFWorkbook) {
    // do whatever
} else if (wb instanceof XSSFWorkbook) {
    // do whatever
}

Anyway if you want to know the real type of the file before using it you can use Apache Tika . 无论如何,如果您想在使用前了解文件的真实类型,可以使用Apache Tika

You can let POI do the job for you, by using WorkbookFactory to automatically have the file extension detected opened for you. 通过使用WorkbookFactory自动为您打开检测到的文件扩展名,可以让POI为您完成任务。

Workbook w = WorkbookFactory.create(new File("hello.xls"));

Of course, you can use Apache Tika to detect the file format for you! 当然,您可以使用Apache Tika为您检测文件格式!

I woul recommend to use this FilenameUtils.getExtension from Apache Commons IO : 我建议从Apache Commons IO使用以下FilenameUtils.getExtension:

String ext = FilenameUtils.getExtension("path to the file"); 字符串ext = FilenameUtils.getExtension(“文件路径”);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM