ITeye博客

java解析获取Excel中的数据--同时兼容2003及2007

ssxxjjii · 2013-04-02 16:06 · core java · 互联网 · Markdown

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

 

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

[java] view plaincopyprint?

  1. package com.execl;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import org.apache.poi.hssf.usermodel.HSSFCell;
  9. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  10. import org.apache.poi.ss.usermodel.Cell;
  11. import org.apache.poi.ss.usermodel.Row;
  12. import org.apache.poi.ss.usermodel.Sheet;
  13. import org.apache.poi.ss.usermodel.Workbook;
  14. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  15. /**
  16. *
  17. * @描述:测试excel读取
  18. *
  19. *               导入的jar包
  20. *
  21. *               poi-3.8-beta3-20110606.jar
  22. *
  23. *               poi-ooxml-3.8-beta3-20110606.jar
  24. *
  25. *               poi-examples-3.8-beta3-20110606.jar
  26. *
  27. *               poi-excelant-3.8-beta3-20110606.jar
  28. *
  29. *               poi-ooxml-schemas-3.8-beta3-20110606.jar
  30. *
  31. *               poi-scratchpad-3.8-beta3-20110606.jar
  32. *
  33. *               xmlbeans-2.3.0.jar
  34. *
  35. *               dom4j-1.6.1.jar
  36. *
  37. *               jar包官网下载地址:http://poi.apache.org/download.html
  38. *
  39. *               下载poi-bin-3.8-beta3-20110606.zipp
  40. *
  41. * @作者:建宁
  42. *
  43. * @时间:2012-08-29 下午16:27:15
  44. */
  45. public class ImportExecl
  46. {
  47. /** 总行数 */
  48. private int totalRows = 0;
  49. /** 总列数 */
  50. private int totalCells = 0;
  51. /** 错误信息 */
  52. private String errorInfo;
  53. /** 构造方法 */
  54. public ImportExecl()
  55. {
  56. }
  57. /**
  58. *
  59. * @描述:得到总行数
  60. *
  61. * @作者:建宁
  62. *
  63. * @时间:2012-08-29 下午16:27:15
  64. *
  65. * @参数:@return
  66. *
  67. * @返回值:int
  68. */
  69. public int getTotalRows()
  70. {
  71. return totalRows;
  72. }
  73. /**
  74. *
  75. * @描述:得到总列数
  76. *
  77. * @作者:建宁
  78. *
  79. * @时间:2012-08-29 下午16:27:15
  80. *
  81. * @参数:@return
  82. *
  83. * @返回值:int
  84. */
  85. public int getTotalCells()
  86. {
  87. return totalCells;
  88. }
  89. /**
  90. *
  91. * @描述:得到错误信息
  92. *
  93. * @作者:建宁
  94. *
  95. * @时间:2012-08-29 下午16:27:15
  96. *
  97. * @参数:@return
  98. *
  99. * @返回值: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<List<String>> read(String filePath)
  151. {
  152. List<List<String>> dataLst = new ArrayList<List<String>>();
  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<List<String>> read(InputStream inputStream, boolean isExcel2003)
  213. {
  214. List<List<String>> 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<List<String>>
  248. */
  249. private List<List<String>> read(Workbook wb)
  250. {
  251. List<List<String>> dataLst = new ArrayList<List<String>>();
  252. /** 得到第一个shell */
  253. Sheet sheet = wb.getSheetAt(0);
  254. /** 得到Excel的行数 */
  255. this.totalRows = sheet.getPhysicalNumberOfRows();
  256. /** 得到Excel的列数 */
  257. if (this.totalRows >= 1 && sheet.getRow(0) != null)
  258. {
  259. this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
  260. }
  261. /** 循环Excel的行 */
  262. for (int r = 0; r < this.totalRows; r++)
  263. {
  264. Row row = sheet.getRow(r);
  265. if (row == null)
  266. {
  267. continue;
  268. }
  269. List<String> rowLst = new ArrayList<String>();
  270. /** 循环Excel的列 */
  271. for (int c = 0; c < 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<List<String>> list = poi.read("d:/aaa.xls");
  328. List<List<String>> list = poi.read("c:/book.xlsx");
  329. if (list != null)
  330. {
  331. for (int i = 0; i < list.size(); i++)
  332. {
  333. System.out.print("第" + (i) + "行");
  334. List<String> cellList = list.get(i);
  335. for (int j = 0; j < 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. }

 

评论(1)

  1. #1 楼 · 贝塔ZQ · 2016-09-29 17:17

    java实现操作excel文件,PageOffice插件可以实现的,兼容03,07office文件,用起来是很方便的。他们官网上有不少事例代码的,可以下载看看,集成起来也方便,可以根据事例进行了解的。

评论功能维护中,当前仅展示历史评论。