读取docx(带图片)

来源:互联网 发布:培训seo 编辑:程序博客网 时间:2024/04/27 13:25
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.List;import java.util.Map;import java.util.UUID;import org.apache.poi.xwpf.usermodel.XWPFDocument;import org.apache.poi.xwpf.usermodel.XWPFParagraph;import org.apache.poi.xwpf.usermodel.XWPFPictureData;import org.apache.poi.xwpf.usermodel.XWPFRun;import com.google.common.collect.Maps;public class Test {public static void main(String[] args){String importPath = "D:/zyk_import/习题模板V1.4(2).docx";String absolutePath = "";try {FileInputStream inputStream = new FileInputStream(importPath);XWPFDocument xDocument = new XWPFDocument(inputStream);List<XWPFParagraph> paragraphs = xDocument.getParagraphs();List<XWPFPictureData> pictures = xDocument.getAllPictures();Map<String, String> map = Maps.newHashMap();for(XWPFPictureData picture : pictures){String id = picture.getPackageRelationship().getId();File folder = new File(absolutePath);if (!folder.exists()) {folder.mkdirs();}String rawName = picture.getFileName();String fileExt = rawName.substring(rawName.lastIndexOf("."));String newName = System.currentTimeMillis() + UUID.randomUUID().toString() + fileExt;File saveFile = new File(absolutePath + File.separator + newName);@SuppressWarnings("resource")FileOutputStream fos = new FileOutputStream(saveFile); fos.write(picture.getData());System.out.println(saveFile.getAbsolutePath());                map.put(id, saveFile.getAbsolutePath());}String text = "";for(XWPFParagraph paragraph : paragraphs){//System.out.println(paragraph.getParagraphText());List<XWPFRun> runs = paragraph.getRuns();for(XWPFRun run : runs){if(run.getCTR().xmlText().indexOf("<w:pict>")!=-1){String runXmlText = run.getCTR().xmlText();int rIdIndex = runXmlText.indexOf("r:id");int rIdEndIndex = runXmlText.indexOf("/>", rIdIndex);String rIdText = runXmlText.substring(rIdIndex, rIdEndIndex);System.out.println(rIdText.split("\"")[1].substring("rId".length()));String id = rIdText.split("\"")[1];System.out.println(map.get(id));text = text +"<img src = '"+map.get(id)+"'/>";}else{text = text + run;}}}System.out.println(text);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

0 2
原创粉丝点击