目标:将word里的图片替换成文本
流程、思想:
读取出Word中的图片 - 存储读取到的图片(提供图片识别原) - 删除Word中的该图片 - 在Word中该图片位置插入替换文字 - 删除存储的图片
Maven依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <!-- poi-实现word文件的读取和修改等操作 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.0.0</version> </dependency> <!-- 针对于2007版(.docx) --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.0</version> </dependency> <!-- 针对于2003版(.doc) --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>4.0.0</version> </dependency> <!-- poi-end -->
|
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| public static void main(String[] args) throws Exception { textReplacePhoto("D:\\Test\\原报格式样例3.docx", "D:\\Test\\原报格式样例3-1.docx","D:/Test/img"); }
public static void textReplacePhoto(String oldFileName, String newFileName, String picturePath) throws Exception { File newFile = new File(newFileName.replace(new File(newFileName).getName(),"")); if (!newFile.exists()){ newFile.mkdirs(); }
if (oldFileName.endsWith(".docx")){ int imgNum=0; InputStream oldIs = new FileInputStream(oldFileName); OutputStream newOs = new FileOutputStream(newFileName); XWPFDocument docx = new XWPFDocument(oldIs); List<XWPFParagraph> paras = docx.getParagraphs(); List<XWPFPictureData> pictures = docx.getAllPictures();
for (XWPFParagraph para:paras){ List<XWPFRun> runList = para.getRuns(); for (int i=0;i<runList.size();i++) { XWPFRun run=runList.get(i); if (!run.getEmbeddedPictures().isEmpty()){ String pictureName=savePictureDocx(pictures,picturePath,imgNum++); if (pictureName!=null){ para.removeRun(i); para.insertNewRun(i).setText("{{title}}"); deletePicture(pictureName); } } } }
docx.write(newOs); docx.close(); oldIs.close(); newOs.flush(); newOs.close(); } }
public static String savePictureDocx(List<XWPFPictureData> pictures, String picturePath,int imgNum) throws IOException { File pictureFile = new File(picturePath); if (!pictureFile.exists()){ pictureFile.mkdirs(); }
List<XWPFPictureData> pictures = para.getDocument().getAllPictures(); if (pictures.size()!=0){ XWPFPictureData picture = pictures.get(imgNum); String rawName = picture.getFileName(); String fileExt = rawName.substring(rawName.lastIndexOf(".")); String newName = System.currentTimeMillis() + UUID.randomUUID().toString() + fileExt; String pictureName = picturePath + File.separator + newName; FileOutputStream fos = new FileOutputStream(pictureName); fos.write(picture.getData());
fos.flush(); fos.close(); return pictureName; } return null; }
public static boolean deletePicture(String pictureName) { File pictureFile = new File(pictureName); return pictureFile.delete(); }
|