java 读取excel文件

原文地址:https://blog.csdn.net/it_wangxiangpan/article/details/42778167

我们使用POI中的HSSFWorkbook来读取Excel数据。

public void test(File file) throws IOException {
 
InputStream inp = new FileInputStream(file);
 
HSSFWorkbook workbook = new HSSFWorkbook(inp);
 
 
// workbook...遍历操作
 
}
View Code

上边代码,读取Excel2003(xls)的文件没问题,但是一旦读取的是Excel2007(xlsx)的文件,就会报异常:

“The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents.

You need to call a different part of POI to process this data (eg XSSF instead of HSSF)”

查阅了资料,Excel2007版本的Excel文件需要使用XSSFWorkbook来读取,如下:

 1  
 2 public void test(File file) throws IOException {
 3  
 4 InputStream inp = new FileInputStream(file);
 5  
 6 XSSFWorkbook workbook = new XSSFWorkbook(inp);
 7  
 8  
 9 // workbook...遍历操作
10  
11 }
View Code

注意:XSSFWorkbook需要额外导入poi-ooxml-3.9-sources.jar和poi-ooxml-schemas-3.9.jar。

这样,Excel2007的导入没问题了,但是导入Excel2003又报异常。

所以,在导入Excel的时候,尽量能判断导入Excel的版本,调用不同的方法。

我想到过使用文件后缀名来判断类型,但是如果有人将xlsx的后缀改为xls时,如果使用xlsx的函数来读取,结果是报错;虽然后缀名对了,但是文件内容编码等都不对。

最后,推荐使用poi-ooxml中的WorkbookFactory.create(inputStream)来创建Workbook,因为HSSFWorkbook和XSSFWorkbook都实现了Workbook接口。代码如下:

Workbook wb = WorkbookFactory.create(is);

可想而知,在WorkbookFactory.create()函数中,肯定有做过对文件类型的判断,一起来看一下源码是如何判断的:

 1 /**
 2  
 3 * Creates the appropriate HSSFWorkbook / XSSFWorkbook from
 4  
 5 * the given InputStream.
 6  
 7 * Your input stream MUST either support mark/reset, or
 8  
 9 * be wrapped as a {@link PushbackInputStream}!
10  
11 */
12  
13 public static Workbook create(InputStream inp) throws IOException, InvalidFormatException {
14  
15 // If clearly doesn't do mark/reset, wrap up
16  
17 if(! inp.markSupported()) {
18  
19 inp = new PushbackInputStream(inp, 8);
20  
21 }
22  
23  
24  
25 if(POIFSFileSystem.hasPOIFSHeader(inp)) {
26  
27 return new HSSFWorkbook(inp);
28  
29 }
30  
31 if(POIXMLDocument.hasOOXMLHeader(inp)) {
32  
33 return new XSSFWorkbook(OPCPackage.open(inp));
34  
35 }
36  
37 throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
38  
39 }
View Code

可以看到,有根据文件类型来分别创建合适的Workbook对象。是根据文件的头部信息去比对进行判断的,此时,就算改了后缀名,还是一样通不过。

原文地址:https://www.cnblogs.com/hm1990hpu/p/9414789.html