1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java之poi读取word文档表格的图片并保存

java之poi读取word文档表格的图片并保存

时间:2023-01-11 01:42:28

相关推荐

java之poi读取word文档表格的图片并保存

遍历读取表格图片

/*** @Description: 获取word文档表格中的所有图片* @Author: wangzhiming* @Date: /6/22 15:51* @Param: doc* @Return: <表格名称,<行索引,<单元格索引,单元格图片集合>>>*/private static HashMap<String, Map<Integer, Map<Integer, List<XWPFPicture>>>> getAllPictures(CustomXWPFDocument doc) {HashMap<String, Map<Integer, Map<Integer, List<XWPFPicture>>>> tableMap = new HashMap<>();//获取文档所有表格并遍历List<XWPFTable> tables = doc.getTables();for(XWPFTable table:tables){//表格名称(根据自己文档的表格名称位置获取)String docTableName = table.getRow(0).getCell(0).getText();List<XWPFTableRow> rows = table.getRows();HashMap<Integer, Map<Integer, List<XWPFPicture>>> rowMap = new HashMap<>();//遍历行for(int m=0;m<rows.size();m++){HashMap<Integer, List<XWPFPicture>> cellMap = new HashMap<>();List<XWPFTableCell> tableCells = rows.get(m).getTableCells();//遍历单元格for(int n=0;n<tableCells.size();n++){XWPFTableCell cell = tableCells.get(n);List<XWPFPicture> pictures=new ArrayList<>();//遍历单元格中所有段落for(int i=0;i<cell.getParagraphs().size();i++){List<XWPFRun> runs = cell.getParagraphs().get(i).getRuns();for(XWPFRun run:runs){String text = run.getText(run.getTextPosition());if(text==null){//说明是附件一类的文件:如图片//获取图片List<XWPFPicture> pictureList = run.getEmbeddedPictures();if(pictureList.size()>0){pictures.addAll(pictureList);}}}}if(pictures.size()>0){cellMap.put(n,pictures);}}if(cellMap.size()>0){rowMap.put(m,cellMap);}}if(rowMap.size()>0){tableMap.put(docTableName,rowMap);}}return tableMap;}

保存图片

/*** @Description: 保存图片* @Author: wangzhiming* @Date: /6/22 15:45* @Param: pictures* @Return: <行索引,<单元格索引,单元格图片以逗号拼接的地址>>*/private Map<Integer, Map<Integer, String>> saveImg(Map<Integer, Map<Integer, List<XWPFPicture>>> pictures) throws IOException {Map<Integer, Map<Integer, String>> map = new HashMap<>();for(Integer rowIndex:pictures.keySet()){Map<Integer, List<XWPFPicture>> cellMap = pictures.get(rowIndex);Map<Integer, String> cellStr= new HashMap<>();for(Integer cellIndex:cellMap.keySet()){List<XWPFPicture> pictureList = cellMap.get(cellIndex);String picStr="";for(XWPFPicture picture:pictureList){//获取图片类型String picType = picture.getPictureData().suggestFileExtension();//拼接图片地址String picPath=imgPath+ File.separator +UUID.randomUUID()+"."+picType;//保存图片FileOutputStream out = new FileOutputStream(picPath);out.write(picture.getPictureData().getData());out.close();//拼接图片地址picStr+=picPath+",";}cellStr.put(cellIndex,picStr.contains(",")?picStr.substring(0,picStr.lastIndexOf(",")):"");}map.put(rowIndex,cellStr);}return map;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。