当前位置:   article > 正文

java利用POI解析Excel及图片_org.apache.poi.xssf.usermodel.xssfsimpleshape cann

org.apache.poi.xssf.usermodel.xssfsimpleshape cannot be cast to org.apache.p

依赖jar

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi</artifactId>
  4. <version>3.17</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.poi</groupId>
  8. <artifactId>poi-ooxml</artifactId>
  9. <version>3.17</version>
  10. </dependency>

代码:

  1. package com.betawoo.admin.test.base;
  2. import com.betawoo.admin.commons.utils.QiNiuUtils;
  3. import org.apache.poi.POIXMLDocumentPart;
  4. import org.apache.poi.hssf.usermodel.*;
  5. import org.apache.poi.ss.usermodel.*;
  6. import org.apache.poi.xssf.usermodel.*;
  7. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
  8. import java.io.File;
  9. import java.io.FileInputStream;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.util.HashMap;
  13. import java.util.List;
  14. import java.util.Map;
  15. /**
  16. * Created by hgg on 2019/5/7.
  17. */
  18. public class POIExcel {
  19. public static void getDataFromExcel(String filePath) throws IOException
  20. {
  21. //判断是否为excel类型文件
  22. if(!filePath.endsWith(".xls")&&!filePath.endsWith(".xlsx"))
  23. {
  24. System.out.println("文件不是excel类型");
  25. }
  26. FileInputStream fis =null;
  27. Workbook wookbook = null;
  28. Sheet sheet =null;
  29. try
  30. {
  31. //获取一个绝对地址的流
  32. fis = new FileInputStream(filePath);
  33. /* 读取网络文件(比如七牛等云存储)
  34. URL url = new URL(filePath);
  35. BufferedInputStream fis = new BufferedInputStream(url.openStream());*/
  36. }
  37. catch(Exception e)
  38. {
  39. e.printStackTrace();
  40. }
  41. try
  42. {
  43. //2003版本的excel,用.xls结尾
  44. wookbook = new HSSFWorkbook(fis);//得到工作簿
  45. }
  46. catch (Exception ex)
  47. {
  48. //ex.printStackTrace();
  49. try
  50. {
  51. //2007版本的excel,用.xlsx结尾
  52. fis = new FileInputStream(filePath);
  53. wookbook = new XSSFWorkbook(fis);//得到工作簿
  54. } catch (IOException e)
  55. {
  56. // TODO Auto-generated catch block
  57. e.printStackTrace();
  58. }
  59. }
  60. Map<String, PictureData> maplist=null;
  61. sheet = wookbook.getSheetAt(0);
  62. // 判断用07还是03的方法获取图片
  63. if (filePath.endsWith(".xls")) {
  64. maplist = getPictures1((HSSFSheet) sheet);
  65. } else if(filePath.endsWith(".xlsx")){
  66. maplist = getPictures2((XSSFSheet) sheet);
  67. }
  68. try {
  69. printImg(maplist);
  70. } catch (Exception e) {
  71. e.printStackTrace();
  72. }finally {
  73. //释放map
  74. if (maplist != null){
  75. maplist = null;
  76. }
  77. }
  78. //得到一个工作表
  79. //获得表头
  80. Row rowHead = sheet.getRow(0);
  81. //获得数据的总行数
  82. int totalRowNum = sheet.getLastRowNum();
  83. //要获得属性
  84. String proName="";
  85. String space="";
  86. String size="";
  87. String brand="";
  88. String unit="";
  89. Integer num=null;
  90. Double unitPrice=null;
  91. Double total=null;
  92. String material="";
  93. String remark="";
  94. String pic="";
  95. //获得所有数据
  96. System.out.println("产品名称\t\t空间\t\t规格/尺寸\t\t品牌\t\t单位\t\t数量\t\t单价\t\t金额\t\t材质\t\t备注");
  97. for(int i = 1 ; i < totalRowNum ; i++)
  98. {
  99. //获得第i行对象
  100. Row row = sheet.getRow(i);
  101. //空间位置(为空则停止解析)
  102. Cell cell = row.getCell(0);
  103. if (cell == null){
  104. break;
  105. }
  106. cell.setCellType(CellType.STRING);
  107. space =cell.getStringCellValue().toString();
  108. if (StringUtils.isBlank(space)){
  109. break;
  110. }
  111. //产品名称
  112. cell = row.getCell(1);
  113. if (cell != null){
  114. cell.setCellType(CellType.STRING);
  115. proName = cell.getStringCellValue();
  116. }
  117. //规格/尺寸
  118. cell = row.getCell(3);
  119. if (cell != null){
  120. cell.setCellType(CellType.STRING);
  121. size =cell.getStringCellValue()+"";
  122. }
  123. //品牌
  124. cell = row.getCell(4);
  125. if (cell != null){
  126. cell.setCellType(CellType.STRING);
  127. brand =cell.getStringCellValue()+"";
  128. }
  129. //单位
  130. cell = row.getCell(5);
  131. if (cell != null){
  132. cell.setCellType(CellType.STRING);
  133. unit =cell.getStringCellValue()+"";
  134. }
  135. //数量
  136. cell = row.getCell(6);
  137. if (cell != null){
  138. num =(int)cell.getNumericCellValue();
  139. }
  140. //单价
  141. cell = row.getCell(7);
  142. if (cell != null){
  143. unitPrice =cell.getNumericCellValue();
  144. }
  145. //金额
  146. cell = row.getCell(8);
  147. if (cell != null){
  148. total =cell.getNumericCellValue();
  149. }
  150. //材质
  151. cell = row.getCell(9);
  152. if (cell != null){
  153. cell.setCellType(CellType.STRING);
  154. material =cell.getStringCellValue()+"";
  155. }
  156. //备注
  157. cell = row.getCell(10);
  158. if (cell != null){
  159. cell.setCellType(CellType.STRING);
  160. remark =cell.getStringCellValue()+"";
  161. }
  162. System.out.println(proName+"\t\t"+space+"\t\t"+size+"\t\t"+brand+"\t\t"+unit+"\t\t"+num+"\t\t"
  163. +unitPrice+"\t\t"+total+"\t\t"+material+"\t\t"+remark);
  164. }
  165. for (Map.Entry<String, PictureData> entry : maplist.entrySet()) {
  166. System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
  167. }
  168. //使用完成关闭
  169. wookbook.close();
  170. if (fis != null){
  171. fis.close();
  172. }
  173. }
  174. /**
  175. * 获取图片和位置 (xls)
  176. * @param sheet
  177. * @return
  178. * @throws IOException
  179. */
  180. public static Map<String, PictureData> getPictures1 (HSSFSheet sheet) throws IOException {
  181. Map<String, PictureData> map = new HashMap<String, PictureData>();
  182. List<HSSFShape> list = sheet.getDrawingPatriarch().getChildren();
  183. for (HSSFShape shape : list) {
  184. if (shape instanceof HSSFPicture) {
  185. HSSFPicture picture = (HSSFPicture) shape;
  186. HSSFClientAnchor cAnchor = (HSSFClientAnchor) picture.getAnchor();
  187. PictureData pdata = picture.getPictureData();
  188. String key = cAnchor.getRow1() + "-" + cAnchor.getCol1(); // 行号-列号
  189. map.put(key, pdata);
  190. }
  191. }
  192. return map;
  193. }
  194. /**
  195. * 获取图片和位置 (xlsx)
  196. * @param sheet
  197. * @return
  198. * @throws IOException
  199. */
  200. public static Map<String, PictureData> getPictures2 (XSSFSheet sheet) throws IOException {
  201. Map<String, PictureData> map = new HashMap<String, PictureData>();
  202. List<POIXMLDocumentPart> list = sheet.getRelations();
  203. for (POIXMLDocumentPart part : list) {
  204. if (part instanceof XSSFDrawing) {
  205. XSSFDrawing drawing = (XSSFDrawing) part;
  206. List<XSSFShape> shapes = drawing.getShapes();
  207. for (XSSFShape shape : shapes) {
  208. XSSFPicture picture = (XSSFPicture) shape;
  209. XSSFClientAnchor anchor = picture.getPreferredSize();
  210. CTMarker marker = anchor.getFrom();
  211. String key = marker.getRow() + "-" + marker.getCol();
  212. map.put(key, picture.getPictureData());
  213. }
  214. }
  215. }
  216. return map;
  217. }
  218. //图片写出
  219. public static void printImg(Map<String, PictureData> sheetList) throws Exception {
  220. Object key[] = sheetList.keySet().toArray();
  221. String filePath = "";
  222. for (int i = 0; i < sheetList.size(); i++) {
  223. // 获取图片流
  224. PictureData pic = sheetList.get(key[i]);
  225. // 获取图片索引
  226. String picName = key[i].toString();
  227. // 获取图片格式
  228. String ext = pic.suggestFileExtension();
  229. byte[] data = pic.getData();
  230. //文件上传七牛
  231. // QiNiuUtils.uploadOneObject(data,"111_"+picName + "." + ext);
  232. //图片保存路径
  233. filePath = "D:\\img\\pic" + picName + "." + ext;
  234. System.out.println(filePath);
  235. FileOutputStream out = new FileOutputStream(filePath);
  236. out.write(data);
  237. out.close();
  238. }
  239. }
  240. public static void main(String[] args) throws Exception {
  241. getDataFromExcel("D:"+ File.separator +"test.xlsx");
  242. }
  243. }

注意事项及测试结果

Excel内容如下:

解析的文本内容,如下

 

解析出的图片

 

缺点或问题:

  1. 单元格图片不能越界(不然解析出来的图片和文本对应关系出错);
  2. 单元格多个图能取到最后一个图;

问题2已找到原因:getPictures1和getPictures2 方法中key导致 ,代码如下
 

  1. String key = cAnchor.getRow1() + "-" + cAnchor.getCol1(); // 行号-列号                
  2. map.put(key, pdata);

至此,试验完全OK~!感谢原文一          感谢原文二

 

扩展:如果是来自外网文件读取方式——感谢思路

  1. BufferedInputStream fis =null;
  2. URL url = new URL(filePath);
  3. fis = new BufferedInputStream(url.openStream());

问题一Cannot get a STRING value from a NUMERIC cell

原因:Excel把纯数字,当做了数值框,导致解析失败

问题二:报错:org..XSSFSimpleShape cannot be cast to ..XSSFPicture

解决办法:将【xlsx】另存为【xls】(因为低版本改成了高版本Excel,解析有问题)

 

补充说明:如果需要读取网络第三方或云存储中的文件(详见代码如下注释内容)

/* 读取网络文件(比如七牛等云存储)
URL url = new URL(filePath);

BufferedInputStream fis = new BufferedInputStream(url.openStream());*/
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/273097
推荐阅读
相关标签
  

闽ICP备14008679号