当前位置:   article > 正文

POI读取Excel中图片_poi读取excel图片

poi读取excel图片
  1. @RequestMapping("importEsComPartsAndPhotoExcel")
  2. public ActionResult getDataFromExcel(@RequestParam(value = "filename") MultipartFile file) throws IOException {
  3. String filename = file.getOriginalFilename();
  4. FileInputStream fis = (FileInputStream) file.getInputStream();
  5. //判断是否为excel类型文件
  6. if (!filename.endsWith(".xls") && !filename.endsWith(".xlsx")) {
  7. System.out.println("文件不是excel类型");
  8. }
  9. Workbook wookbook = null;
  10. Sheet sheet = null;
  11. try {
  12. //2007版本的excel,用.xlsx结尾
  13. wookbook = new XSSFWorkbook(fis);//得到工作簿
  14. } catch (IOException e) {
  15. e.printStackTrace();
  16. }
  17. Map<String, PictureData> maplist = null;
  18. sheet = (Sheet) wookbook.getSheetAt(0);
  19. // 判断用07还是03的方法获取图片
  20. if (filename.endsWith(".xls")) {
  21. maplist = getPictures1((HSSFSheet) sheet);
  22. } else if (filename.endsWith(".xlsx")) {
  23. maplist = getPictures2((XSSFSheet) sheet);
  24. }
  25. Map<String,String> map = null;
  26. try {
  27. map = printImg(maplist);
  28. } catch (Exception e) {
  29. Log.error(e.getMessage(),e);
  30. } finally {
  31. //释放map
  32. if (maplist != null) {
  33. maplist = null;
  34. }
  35. }
  36. //得到一个工作表
  37. //获得表头
  38. // Row rowHead = sheet.getRow(0);
  39. //获得数据的总行数
  40. int totalRowNum = sheet.getLastRowNum();
  41. //要获得属性
  42. String code = "";
  43. try{
  44. //获得所有数据
  45. for (int i = 0; i <= totalRowNum; i++) {
  46. //获得第i行对象
  47. Row row = sheet.getRow(i);
  48. Cell cell = row.getCell(0);
  49. if (cell == null) {
  50. continue;
  51. }
  52. cell.setCellType(CellType.STRING);
  53. code = cell.getStringCellValue().toString();
  54. if (StringUtils.isEmpty(code)) {
  55. break;
  56. }
  57. EsComParts ecd = escompartsService.getPartsByCode(code);
  58. if(ecd != null) {
  59. String partsPhoto = StringUtils.changeToString(ecd.getFparts_photo());
  60. if(StringUtils.equals(partsPhoto, "")) {
  61. String photoPath = StringUtils.changeToString(map.get(i+""));
  62. if(!StringUtils.equals(photoPath, "")) {
  63. File filePhoto = new File(photoPath);
  64. MultipartFile Photo = getMultipartFile(filePhoto);
  65. MultipartFile[] Photos = {Photo};
  66. if(Photos != null) {
  67. ecd.setFparts_photo(PhotoForOSSUtils.changePhotoToString(Photos));
  68. escompartsService.update(ecd);
  69. }
  70. }
  71. }
  72. }
  73. }
  74. }catch (Exception e){
  75. System.out.println("数据不符合规范");
  76. }
  77. //使用完成关闭
  78. wookbook.close();
  79. if (fis != null) {
  80. fis.close();
  81. }
  82. return ActionResult.Succeed("导入成功!");
  83. }
  1. public static void inputStreamToFile(InputStream ins, File file) {
  2. try {
  3. OutputStream os = new FileOutputStream(file);
  4. int bytesRead = 0;
  5. byte[] buffer = new byte[8192];
  6. while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
  7. os.write(buffer, 0, bytesRead);
  8. }
  9. os.close();
  10. ins.close();
  11. } catch (Exception e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. @SuppressWarnings("unused")
  16. @RequestMapping("importEsComPartsAndPhotoExcel")
  17. public ActionResult getDataFromExcel(@RequestParam(value = "filename") MultipartFile file) throws IOException {
  18. String filename = file.getOriginalFilename();
  19. FileInputStream fis = (FileInputStream) file.getInputStream();
  20. //判断是否为excel类型文件
  21. if (!filename.endsWith(".xls") && !filename.endsWith(".xlsx")) {
  22. System.out.println("文件不是excel类型");
  23. }
  24. Workbook wookbook = null;
  25. Sheet sheet = null;
  26. try {
  27. //2007版本的excel,用.xlsx结尾
  28. wookbook = new XSSFWorkbook(fis);//得到工作簿
  29. } catch (IOException e) {
  30. e.printStackTrace();
  31. }
  32. Map<String, PictureData> maplist = null;
  33. sheet = (Sheet) wookbook.getSheetAt(0);
  34. // 判断用07还是03的方法获取图片
  35. if (filename.endsWith(".xls")) {
  36. maplist = getPictures1((HSSFSheet) sheet);
  37. } else if (filename.endsWith(".xlsx")) {
  38. maplist = getPictures2((XSSFSheet) sheet);
  39. }
  40. Map<String,String> map = null;
  41. try {
  42. map = printImg(maplist);
  43. } catch (Exception e) {
  44. Log.error(e.getMessage(),e);
  45. } finally {
  46. //释放map
  47. if (maplist != null) {
  48. maplist = null;
  49. }
  50. }
  51. //得到一个工作表
  52. //获得表头
  53. // Row rowHead = sheet.getRow(0);
  54. //获得数据的总行数
  55. int totalRowNum = sheet.getLastRowNum();
  56. //要获得属性
  57. String code = "";
  58. try{
  59. //获得所有数据
  60. for (int i = 0; i <= totalRowNum; i++) {
  61. //获得第i行对象
  62. Row row = sheet.getRow(i);
  63. Cell cell = row.getCell(0);
  64. if (cell == null) {
  65. continue;
  66. }
  67. cell.setCellType(CellType.STRING);
  68. code = cell.getStringCellValue().toString();
  69. if (StringUtils.isEmpty(code)) {
  70. break;
  71. }
  72. EsComParts ecd = escompartsService.getPartsByCode(code);
  73. if(ecd != null) {
  74. String partsPhoto = StringUtils.changeToString(ecd.getFparts_photo());
  75. if(StringUtils.equals(partsPhoto, "")) {
  76. String photoPath = StringUtils.changeToString(map.get(i+""));
  77. if(!StringUtils.equals(photoPath, "")) {
  78. File filePhoto = new File(photoPath);
  79. MultipartFile Photo = getMultipartFile(filePhoto);
  80. MultipartFile[] Photos = {Photo};
  81. if(Photos != null) {
  82. ecd.setFparts_photo(PhotoForOSSUtils.changePhotoToString(Photos));
  83. escompartsService.update(ecd);
  84. }
  85. }
  86. }
  87. }
  88. }
  89. }catch (Exception e){
  90. System.out.println("数据不符合规范");
  91. }
  92. //使用完成关闭
  93. wookbook.close();
  94. if (fis != null) {
  95. fis.close();
  96. }
  97. return ActionResult.Succeed("导入成功!");
  98. }
  99. /**
  100. * 获取图片和位置 (xls)
  101. *
  102. * @param sheet
  103. * @return
  104. * @throws IOException
  105. */
  106. public Map<String, PictureData> getPictures1(HSSFSheet sheet) throws IOException {
  107. Map<String, PictureData> map = new HashMap<String, PictureData>();
  108. List<HSSFShape> list = sheet.getDrawingPatriarch().getChildren();
  109. for (HSSFShape shape : list) {
  110. if (shape instanceof HSSFPicture) {
  111. HSSFPicture picture = (HSSFPicture) shape;
  112. HSSFClientAnchor cAnchor = (HSSFClientAnchor) picture.getAnchor();
  113. PictureData pdata = picture.getPictureData();
  114. String key = cAnchor.getRow1() + "-" + cAnchor.getCol1(); // 行号-列号
  115. String proName = sheet.getRow(cAnchor.getRow1()).getCell(0).getStringCellValue();
  116. if(cAnchor.getCol1()==1){
  117. key = proName+="01";
  118. }else if(cAnchor.getCol1()==11){
  119. key = proName+="02";
  120. }
  121. map.put(key, pdata);
  122. }
  123. }
  124. return map;
  125. }
  126. /**
  127. * 获取图片和位置 (xlsx)
  128. *
  129. * @param sheet
  130. * @return
  131. * @throws IOException
  132. */
  133. public Map<String, PictureData> getPictures2(XSSFSheet sheet) throws IOException {
  134. Map<String, PictureData> map = new HashMap<String, PictureData>();
  135. List<POIXMLDocumentPart> list = sheet.getRelations();
  136. for (POIXMLDocumentPart part : list) {
  137. if (part instanceof XSSFDrawing) {
  138. XSSFDrawing drawing = (XSSFDrawing) part;
  139. List<XSSFShape> shapes = drawing.getShapes();
  140. for (XSSFShape shape : shapes) {
  141. XSSFPicture picture = (XSSFPicture) shape;
  142. XSSFClientAnchor anchor = picture.getPreferredSize();
  143. CTMarker marker = anchor.getFrom();
  144. int rowNum = marker.getRow();
  145. int colNum = marker.getCol();
  146. String key = marker.getRow() + "";
  147. // String key = marker.getRow() + "-" + marker.getCol();
  148. System.out.println(colNum);
  149. if(colNum==1){
  150. if(picture.getPictureData().getData().length<120*1024){
  151. map.put(key, picture.getPictureData());
  152. }else{
  153. // 主图大小不符合要求
  154. System.out.println(String.format("{}行{}列主图大小不符合要求",rowNum,colNum));
  155. }
  156. map.put(key, picture.getPictureData());
  157. }
  158. }
  159. }
  160. }
  161. return map;
  162. }
  163. /**
  164. * 删除文件
  165. *
  166. * @param fileName 文件名
  167. * @return 删除成功返回true,失败返回false
  168. */
  169. public static boolean deleteFile(String fileName) {
  170. File file = new File(fileName);
  171. if (file.isFile() && file.exists()) {
  172. file.delete();
  173. return true;
  174. } else {
  175. return false;
  176. }
  177. }
  178. /**
  179. * 图片写出
  180. *
  181. * @param sheetList
  182. * @throws Exception
  183. */
  184. public static Map<String,String> printImg(Map<String, PictureData> sheetList) throws Exception {
  185. Map<String,String> map = new HashMap<>();
  186. Object key[] = sheetList.keySet().toArray();
  187. String filePath = "";
  188. File delPath = new File("/work/poi");
  189. // File delPath = new File("D://poi");
  190. boolean flag = true;
  191. // 删除文件夹下的所有文件和文件夹
  192. File[] fileStr = delPath.listFiles();
  193. for (int i = 0; i < fileStr.length; i++) { // 循环删除所有的子文件
  194. // 删除子文件
  195. if (fileStr[i].isFile()) {
  196. flag = deleteFile(fileStr[i].getAbsolutePath());
  197. if (!flag) {
  198. break;
  199. }
  200. }
  201. }
  202. delPath.delete();
  203. File files = new File("/work/poi");
  204. // File files=new File("D://poi");
  205. files.mkdirs();
  206. for (int i = 0; i < sheetList.size(); i++) {
  207. // 获取图片流
  208. PictureData pic = sheetList.get(key[i]);
  209. // 获取图片索引
  210. String picName = key[i].toString();
  211. // 获取图片格式
  212. String ext = pic.suggestFileExtension();
  213. byte[] data = pic.getData();
  214. filePath = "/work/poi/" + picName + "." + ext;
  215. // filePath = "D://poi/" + picName + "." + ext;
  216. map.put(picName, filePath);
  217. FileOutputStream out = new FileOutputStream(filePath);
  218. out.write(data);
  219. out.close();
  220. }
  221. return map;
  222. }
  223. public static MultipartFile getMultipartFile(File file) {
  224. FileItem item = new DiskFileItemFactory().createItem("file"
  225. , MediaType.MULTIPART_FORM_DATA_VALUE
  226. , true
  227. , file.getName());
  228. try (InputStream input = new FileInputStream(file);
  229. OutputStream os = item.getOutputStream()) {
  230. // 流转移
  231. IOUtils.copy(input, os);
  232. } catch (Exception e) {
  233. throw new IllegalArgumentException("Invalid file: " + e, e);
  234. }
  235. return new CommonsMultipartFile(item);
  236. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/273058
推荐阅读
相关标签
  

闽ICP备14008679号