---
title: "java解析获取Excel中的数据－－同时兼容2003及2007"
author: "ssxxjjii"
date: "2013-04-02T16:06:58Z"
tags: []
categories: ["互联网"]
slug: "java-excel-2003-2007"
draft: false
lastmod: "2013-04-02T16:06:58Z"
id: 1840825
url: "https://tdcq.iteye.com/blog/1840825"
---

java解析Excel（兼容2003及2007）

刚开始从网上找了个例子使用new HSSFWorkbook(new FileInputStream(excelFile))来读取Workbook，  
对Excel2003以前（包括2003）的版本没有问题，但读取Excel2007时发生如下异常：  
org.apache.poi.poifs.filesystem.OfficeXmlFileException: 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)

        该错误意思是说，文件中的数据是用Office2007+XML保存的，而现在却调用OLE2 Office文档处理，应该使用POI不同的部分来处理这些数据，比如使用XSSF来代替HSSF。

        于是按提示使用XSSF代替HSSF，用new XSSFWorkbook(excelFile)来读取Workbook，对Excel2007没有问题了，可是在读取Excel2003以前（包括2003）的版本时却发生了如下新异常：  
org.apache.poi.openxml4j.exceptions.InvalidOperationException: Can't open the specified file: '\*.xls'  
        该错误是说，操作无效，不能打开指定的xls文件。

        到网上查了下，原来是XSSF不能读取Excel2003以前（包括2003）的版本，这样的话，就需要在读取前判断文件是2003前的版本还是2007的版本，然后对应调用HSSF或XSSF来读取。  
        这种做法比较麻烦，看了下API，发现XSSF和HSSF虽然在不同的包里，但却引用了同一接口Workbook，于是想到了这样的读取方法：  
        Workbook book = null;  
        try {  
            book = new XSSFWorkbook(excelFile);  
        } catch (Exception ex) {  
            book = new HSSFWorkbook(new FileInputStream(excelFile));  
        }  
          
本认为程序应该没错了吧，但一运行还是报错（当时用得是poi3.6的zip包）：

java.lang.ClassNotFoundException: org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheet

网上搜了下，是少poi-ooxml-schemas-xxx.jar包，根据提示在Apache网站上（http://labs.renren.com/apache-mirror//poi/release/bin/）下载了3.7的zip文件（poi-bin-3.7-20101029.zip），解压后将poi相关的包和xml相关的包都放上去。

在各版本的Excel中测试，没有发生异常，问题解决。

下面是POI的API网址，不过是英文的：  
POI API Documentation  
[http://poi.apache.org/apidocs/index.html](http://poi.apache.org/apidocs/index.html)

 

　　　转入正题：以下是代码，代码也是从别人的代码拿过来的，其中修改了部分

**\[java]** [view plain](http://blog.csdn.net/mmm333zzz/article/details/7962377 "view plain")[copy](http://blog.csdn.net/mmm333zzz/article/details/7962377 "copy")[print](http://blog.csdn.net/mmm333zzz/article/details/7962377 "print")[?](http://blog.csdn.net/mmm333zzz/article/details/7962377 "?")

001. package com.execl;
002. import java.io.File;
003. import java.io.FileInputStream;
004. import java.io.IOException;
005. import java.io.InputStream;
006. import java.util.ArrayList;
007. import java.util.List;
008. import org.apache.poi.hssf.usermodel.HSSFCell;
009. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
010. import org.apache.poi.ss.usermodel.Cell;
011. import org.apache.poi.ss.usermodel.Row;
012. import org.apache.poi.ss.usermodel.Sheet;
013. import org.apache.poi.ss.usermodel.Workbook;
014. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
015. /\**
016. \*
017. * @描述：测试excel读取
018. \*
019. *               导入的jar包
020. \*
021. *               poi-3.8-beta3-20110606.jar
022. \*
023. *               poi-ooxml-3.8-beta3-20110606.jar
024. \*
025. *               poi-examples-3.8-beta3-20110606.jar
026. \*
027. *               poi-excelant-3.8-beta3-20110606.jar
028. \*
029. *               poi-ooxml-schemas-3.8-beta3-20110606.jar
030. \*
031. *               poi-scratchpad-3.8-beta3-20110606.jar
032. \*
033. *               xmlbeans-2.3.0.jar
034. \*
035. *               dom4j-1.6.1.jar
036. \*
037. *               jar包官网下载地址：http://poi.apache.org/download.html
038. \*
039. *               下载poi-bin-3.8-beta3-20110606.zipp
040. \*
041. * @作者：建宁
042. \*
043. * @时间：2012-08-29 下午16:27:15
044. \*/
045. public class ImportExecl
046. {
047. /\** 总行数 \*/
048. private int totalRows = 0;
049. /\** 总列数 \*/
050. private int totalCells = 0;
051. /\** 错误信息 \*/
052. private String errorInfo;
053. /\** 构造方法 \*/
054. public ImportExecl()
055. {
056. }
057. /\**
058. \*
059. * @描述：得到总行数
060. \*
061. * @作者：建宁
062. \*
063. * @时间：2012-08-29 下午16:27:15
064. \*
065. * @参数：@return
066. \*
067. * @返回值：int
068. \*/
069. public int getTotalRows()
070. {
071. return totalRows;
072. }
073. /\**
074. \*
075. * @描述：得到总列数
076. \*
077. * @作者：建宁
078. \*
079. * @时间：2012-08-29 下午16:27:15
080. \*
081. * @参数：@return
082. \*
083. * @返回值：int
084. \*/
085. public int getTotalCells()
086. {
087. return totalCells;
088. }
089. /\**
090. \*
091. * @描述：得到错误信息
092. \*
093. * @作者：建宁
094. \*
095. * @时间：2012-08-29 下午16:27:15
096. \*
097. * @参数：@return
098. \*
099. * @返回值：String
100. \*/
101. public String getErrorInfo()
102. {
103. return errorInfo;
104. }
105. /\**
106. \*
107. * @描述：验证excel文件
108. \*
109. * @作者：建宁
110. \*
111. * @时间：2012-08-29 下午16:27:15
112. \*
113. * @参数：@param filePath　文件完整路径
114. \*
115. * @参数：@return
116. \*
117. * @返回值：boolean
118. \*/
119. public boolean validateExcel(String filePath)
120. {
121. /\** 检查文件名是否为空或者是否是Excel格式的文件 \*/
122. if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath)))
123. {
124. errorInfo = "文件名不是excel格式";
125. return false;
126. }
127. /\** 检查文件是否存在 \*/
128. File file = new File(filePath);
129. if (file == null || !file.exists())
130. {
131. errorInfo = "文件不存在";
132. return false;
133. }
134. return true;
135. }
136. /\**
137. \*
138. * @描述：根据文件名读取excel文件
139. \*
140. * @作者：建宁
141. \*
142. * @时间：2012-08-29 下午16:27:15
143. \*
144. * @参数：@param filePath 文件完整路径
145. \*
146. * @参数：@return
147. \*
148. * @返回值：List
149. \*/
150. public List&lt;List&lt;String&gt;&gt; read(String filePath)
151. {
152. List&lt;List&lt;String&gt;&gt; dataLst = new ArrayList&lt;List&lt;String&gt;&gt;();
153. InputStream is = null;
154. try
155. {
156. /\** 验证文件是否合法 \*/
157. if (!validateExcel(filePath))
158. {
159. System.out.println(errorInfo);
160. return null;
161. }
162. /\** 判断文件的类型，是2003还是2007 \*/
163. boolean isExcel2003 = true;
164. if (WDWUtil.isExcel2007(filePath))
165. {
166. isExcel2003 = false;
167. }
168. /\** 调用本类提供的根据流读取的方法 \*/
169. File file = new File(filePath);
170. is = new FileInputStream(file);
171. dataLst = read(is, isExcel2003);
172. is.close();
173. }
174. catch (Exception ex)
175. {
176. ex.printStackTrace();
177. }
178. finally
179. {
180. if (is != null)
181. {
182. try
183. {
184. is.close();
185. }
186. catch (IOException e)
187. {
188. is = null;
189. e.printStackTrace();
190. }
191. }
192. }
193. /\** 返回最后读取的结果 \*/
194. return dataLst;
195. }
196. /\**
197. \*
198. * @描述：根据流读取Excel文件
199. \*
200. * @作者：建宁
201. \*
202. * @时间：2012-08-29 下午16:40:15
203. \*
204. * @参数：@param inputStream
205. \*
206. * @参数：@param isExcel2003
207. \*
208. * @参数：@return
209. \*
210. * @返回值：List
211. \*/
212. public List&lt;List&lt;String&gt;&gt; read(InputStream inputStream, boolean isExcel2003)
213. {
214. List&lt;List&lt;String&gt;&gt; dataLst = null;
215. try
216. {
217. /\** 根据版本选择创建Workbook的方式 \*/
218. Workbook wb = null;
219. if (isExcel2003)
220. {
221. wb = new HSSFWorkbook(inputStream);
222. }
223. else
224. {
225. wb = new XSSFWorkbook(inputStream);
226. }
227. dataLst = read(wb);
228. }
229. catch (IOException e)
230. {
231. e.printStackTrace();
232. }
233. return dataLst;
234. }
235. /\**
236. \*
237. * @描述：读取数据
238. \*
239. * @作者：建宁
240. \*
241. * @时间：2012-08-29 下午16:50:15
242. \*
243. * @参数：@param Workbook
244. \*
245. * @参数：@return
246. \*
247. * @返回值：List&lt;List&lt;String&gt;&gt;
248. \*/
249. private List&lt;List&lt;String&gt;&gt; read(Workbook wb)
250. {
251. List&lt;List&lt;String&gt;&gt; dataLst = new ArrayList&lt;List&lt;String&gt;&gt;();
252. /\** 得到第一个shell \*/
253. Sheet sheet = wb.getSheetAt(0);
254. /\** 得到Excel的行数 \*/
255. this.totalRows = sheet.getPhysicalNumberOfRows();
256. /\** 得到Excel的列数 \*/
257. if (this.totalRows &gt;= 1 && sheet.getRow(0) != null)
258. {
259. this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
260. }
261. /\** 循环Excel的行 \*/
262. for (int r = 0; r &lt; this.totalRows; r++)
263. {
264. Row row = sheet.getRow(r);
265. if (row == null)
266. {
267. continue;
268. }
269. List&lt;String&gt; rowLst = new ArrayList&lt;String&gt;();
270. /\** 循环Excel的列 \*/
271. for (int c = 0; c &lt; this.getTotalCells(); c++)
272. {
273. Cell cell = row.getCell(c);
274. String cellValue = "";
275. if (null != cell)
276. {
277. // 以下是判断数据的类型
278. switch (cell.getCellType())
279. {
280. case HSSFCell.CELL\_TYPE\_NUMERIC: // 数字
281. cellValue = cell.getNumericCellValue() + "";
282. break;
283. case HSSFCell.CELL\_TYPE\_STRING: // 字符串
284. cellValue = cell.getStringCellValue();
285. break;
286. case HSSFCell.CELL\_TYPE\_BOOLEAN: // Boolean
287. cellValue = cell.getBooleanCellValue() + "";
288. break;
289. case HSSFCell.CELL\_TYPE\_FORMULA: // 公式
290. cellValue = cell.getCellFormula() + "";
291. break;
292. case HSSFCell.CELL\_TYPE\_BLANK: // 空值
293. cellValue = "";
294. break;
295. case HSSFCell.CELL\_TYPE\_ERROR: // 故障
296. cellValue = "非法字符";
297. break;
298. default:
299. cellValue = "未知类型";
300. break;
301. }
302. }
303. rowLst.add(cellValue);
304. }
305. /\** 保存第r行的第c列 \*/
306. dataLst.add(rowLst);
307. }
308. return dataLst;
309. }
310. /\**
311. \*
312. * @描述：main测试方法
313. \*
314. * @作者：建宁
315. \*
316. * @时间：2012-08-29 下午17:12:15
317. \*
318. * @参数：@param args
319. \*
320. * @参数：@throws Exception
321. \*
322. * @返回值：void
323. \*/
324. public static void main(String\[] args) throws Exception
325. {
326. ImportExecl poi = new ImportExecl();
327. // List&lt;List&lt;String&gt;&gt; list = poi.read("d:/aaa.xls");
328. List&lt;List&lt;String&gt;&gt; list = poi.read("c:/book.xlsx");
329. if (list != null)
330. {
331. for (int i = 0; i &lt; list.size(); i++)
332. {
333. System.out.print("第" + (i) + "行");
334. List&lt;String&gt; cellList = list.get(i);
335. for (int j = 0; j &lt; cellList.size(); j++)
336. {
337. // System.out.print("    第" + (j + 1) + "列值：");
338. System.out.print("    " + cellList.get(j));
339. }
340. System.out.println();
341. }
342. }
343. }
344. }
345. /\**
346. \*
347. * @描述：工具类
348. \*
349. * @作者：建宁
350. \*
351. * @时间：2012-08-29 下午16:30:40
352. \*/
353. class WDWUtil
354. {
355. /\**
356. \*
357. * @描述：是否是2003的excel，返回true是2003
358. \*
359. * @作者：建宁
360. \*
361. * @时间：2012-08-29 下午16:29:11
362. \*
363. * @参数：@param filePath　文件完整路径
364. \*
365. * @参数：@return
366. \*
367. * @返回值：boolean
368. \*/
369. public static boolean isExcel2003(String filePath)
370. {
371. return filePath.matches("^.+\\\\.(?i)(xls)$");
372. }
373. /\**
374. \*
375. * @描述：是否是2007的excel，返回true是2007
376. \*
377. * @作者：建宁
378. \*
379. * @时间：2012-08-29 下午16:28:20
380. \*
381. * @参数：@param filePath　文件完整路径
382. \*
383. * @参数：@return
384. \*
385. * @返回值：boolean
386. \*/
387. public static boolean isExcel2007(String filePath)
388. {
389. return filePath.matches("^.+\\\\.(?i)(xlsx)$");
390. }
391. }

 

![](http://img.my.csdn.net/uploads/201209/10/1347245195_7043.png)

![](http://img.my.csdn.net/uploads/201209/10/1347245206_1581.png)