遍历读取表格图片
private static HashMap>>> getAllPictures(CustomXWPFDocument doc) {
HashMap>>> tableMap = new HashMap<>();
//获取文档所有表格并遍历
List tables = doc.getTables();
for(XWPFTable table:tables){
//表格名称(根据自己文档的表格名称位置获取)
String docTableName = table.getRow(0).getCell(0).getText();
List rows = table.getRows();
HashMap>> rowMap = new HashMap<>();
//遍历行
for(int m=0;m
HashMap> cellMap = new HashMap<>();
List tableCells = rows.get(m).getTableCells();
//遍历单元格
for(int n=0;n
XWPFTableCell cell = tableCells.get(n);
List pictures=new ArrayList<>();
//遍历单元格中所有段落
for(int i=0;i
List runs = cell.getParagraphs().get(i).getRuns();
for(XWPFRun run:runs){
String text = run.getText(run.getTextPosition());
if(text==null){//说明是附件一类的文件:如图片
//获取图片
List 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;
}
保存图片
private Map> saveImg(Map>> pictures) throws IOException {
Map> map = new HashMap<>();
for(Integer rowIndex:pictures.keySet()){
Map> cellMap = pictures.get(rowIndex);
Map cellStr= new HashMap<>();
for(Integer cellIndex:cellMap.keySet()){
List 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;
}