JAVA使用POI向doc加入圖片
前言
剛來一個需求需要導出一個word文檔,文檔內是系統某個界面的各種數據圖表,以圖片的方式插入后導出。一番查閱資料于是乎著手開始編寫簡化demo,有關參考poi的文檔查閱 Apache POI Word(docx) 入門示例教程
網上大多數是XXX模板占位然后插入圖片,那種方式需要內置模板且圖片需要轉base64,并不是我想要的,我的需求很簡單只要無腦插入導出即可。先上demo效果圖。
注意:代碼中寬高的單位一定要使用Units.toEMU(XXX)處理一下,否則就會出現插進去了但是你看不到效果的情況
依賴
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency>
單元測試參考代碼
@Slf4j
public class ImgDocTest {@Testvoid testExportDocContainsImg() throws IOException, InvalidFormatException {File dir = new File("D:\\tmp\\tmp\\20231208");File[] imagePaths = dir.listFiles();addImagesToWord(imagePaths);}private static void addImagesToWord(File[] imgs) throws IOException, InvalidFormatException {try (XWPFDocument document = new XWPFDocument()) {for (File img : imgs) {// 只對指定后綴的圖片處理if (img.getName().endsWith("jpeg") || img.getName().endsWith("jpg") || img.getName().endsWith("png")) {BufferedImage bufferedImage = ImageIO.read(img);int imageType = XWPFDocument.PICTURE_TYPE_JPEG;if (img.getName().endsWith(".png")) {imageType = XWPFDocument.PICTURE_TYPE_PNG;}int width = bufferedImage.getWidth();int height = bufferedImage.getHeight();// Create a new run and add the imageXWPFRun run = document.createParagraph().createRun();log.warn("fileName:{},height:{},width:{}", img.getName(), height, width);run.addPicture(new FileInputStream(img), imageType, img.getName(), Units.toEMU(width), Units.toEMU(height));// Optionally, you can add more text or formatting here// Add a new line for the next imagedocument.createParagraph();} else {continue;}// Save the modified documenttry (FileOutputStream fos = new FileOutputStream("D:\\tmp\\tmp\\20231208\\modify.doc")) {document.write(fos);System.out.println("Images added to Word document successfully.");}}}}
}
參考資料
- Apache POI Word(docx) 入門示例教程
- 插入圖片顯示不了的問題