1. 程式人生 > 實用技巧 >POI 操作Word, 向Word中寫入文字,圖片.

POI 操作Word, 向Word中寫入文字,圖片.

主要是Word中寫入圖片

1. 圖片操作工具類

package cn.elaixin.util;

import org.apache.commons.compress.utils.IOUtils;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import
java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.FileInputStream; /** * Copyright (c) 2020 * @Author: C.S * @LastModified: 2020/7/26 18:04 */ public class ImageUtils { /** * 將base64碼轉成位元組陣列輸入流 * @param imgStr * @return */ public static ByteArrayInputStream getImgByBase64Str(String imgStr) {//
對位元組陣列字串進行Base64解碼並生成圖片 if (imgStr == null) // 影象資料為空 return null; BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解碼 byte[] bytes = decoder.decodeBuffer(imgStr); for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 調整異常資料 bytes[i] += 256; } } return new ByteArrayInputStream(bytes); } catch (Exception e) { return null; } } /** * 根據圖片路徑獲取圖片 * @param path * @return * @throws Exception */ public static BufferedImage getImgByFilePath(String path) throws Exception { FileInputStream fis = new FileInputStream(path); byte[] byteArray = IOUtils.toByteArray(fis); ByteArrayInputStream bais = new ByteArrayInputStream(byteArray); return ImageIO.read(bais); } /** * 向Word中插入圖片(僅支援png格式圖片, 未完待續...) * @param run * @param imagePath 圖片檔案路徑 * @throws Exception */ public static void writeImage(XWPFRun run, String imagePath) throws Exception { BufferedImage image = getImgByFilePath(imagePath); int width = Units.toEMU(image.getWidth()); int height = Units.toEMU(image.getHeight()); run.addPicture(new FileInputStream(imagePath), XWPFDocument.PICTURE_TYPE_PNG, "test", width, height); } }

2. 寫入圖片示例

package cn.elaixin.test;

import cn.elaixin.util.ImageUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.FileOutputStream;

/**
 * Copyright (c) 2020
 * @Author: C.S
 * @LastModified: 2020/7/26 18:06
 */
public class ImgToWordTest {


    public static void main(String[] args) throws Exception {
        writeToWord();
    }

    /**
     * Word中寫入圖片示例
     * @throws Exception
     */
    public static void writeToWord() throws Exception {
        FileOutputStream fos = new FileOutputStream("F:\\wordFile\\temp.docx");
        String imgPath = "C:\\Users\\Administrator\\Desktop\\test\\test.png";   // 圖片路徑
        XWPFDocument document = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        ImageUtils.writeImage(run, imgPath);
        document.write(fos);
        System.out.println("=========Word檔案生成成功==========");
    }

}

3. 寫入圖片以及文字示例

package cn.elaixin.test;

import cn.elaixin.entity.TextInfo;
import cn.elaixin.util.ImageUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.FileOutputStream;
import java.util.*;

/**
 * Copyright (c) 2020
 * @Author: C.S
 * @LastModified: 2020/7/26 18:08
 */
public class HtmlToWordTest {

    public static void main(String[] args) throws Exception {
        String html = "<div class=\"richTxt\">\n" +
                "\t<span style=\"font-size: 20px;color: #000000;font-family: cursive;\">哈哈哈</span>\n" +
                "\t<span style=\"font-size: 15px;color: #000000\">嘿嘿嘿</span>\n" +
                "\t<span style=\"font-size: 17px;color: #000000\">呵呵呵</span>\n" +
                "\t<strong style=\"color: #000000;font-size: 14px\">上課了更好</strong>\n" +
                "</div>";

        writeToWord(html);
    }

    /**
     * 解析Html
     * @param html
     * @return
     */
    public static List<TextInfo> parseHtml(String html) {
        List<TextInfo> contents = new ArrayList<>();
        Document document = Jsoup.parse(html);
        Elements spans = document.select("div.richTxt>*");
        for (Element ele : spans) {
            String text = ele.text();
            Map<String, String> styleMap = getTextElementStyle(ele);
            TextInfo tInfo = new TextInfo();
            tInfo.setText(text);
            tInfo.setStyleMap(styleMap);
            contents.add(tInfo);
        }
        return contents;
    }

    /**
     * 將內容寫入Word
     * @param html
     * @throws Exception
     */
    public static void writeToWord(String html) throws Exception {
        List<TextInfo> textInfos = parseHtml(html);
        FileOutputStream fos = new FileOutputStream("F:\\wordFile\\temp.docx");
        XWPFDocument document = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        String imgPath = "C:\\Users\\Administrator\\Desktop\\test\\test.png";   // 圖片路徑
        for (TextInfo textInfo : textInfos) {
            XWPFRun run = paragraph.createRun();
            Map<String, String> styleMap = textInfo.getStyleMap();
            // 設定樣式
            setFontStyle(run, styleMap);
            // 設定文字
            run.setText(textInfo.getText());

            if ("嘿嘿嘿".equals(textInfo.getText())) {
                ImageUtils.writeImage(run, imgPath);
            }

        }

        document.write(fos);
        System.out.println("=========Word檔案生成成功==========");
    }

    /**
     * 設定字型
     * @param run
     * @param styleMap
     */
    public static void setFontStyle(XWPFRun run, Map<String, String> styleMap) {
        Set<String> styleNameSet = styleMap.keySet();
        for (String styleName : styleNameSet) {
            switch (styleName) {
                case "font-family":
                    run.setFontFamily(styleMap.get(styleName));
                    break;
                case "font-size":
                    run.setFontSize(Integer.valueOf(styleMap.get(styleName)));
                    break;
                case "color":
                    run.setColor(styleMap.get(styleName));
                    break;
                case "isBold":
                    run.setBold(true);
                    break;
            }
        }

    }

    /**
     *  獲取文字元素的樣式集
     * @param e
     * @return
     */
    public static Map<String, String> getTextElementStyle(Element e) {
        Map<String, String> styleMap = new HashMap<>();

        if ("strong".equals(e.tagName())) {
            styleMap.put("isBold", "true");
        }

        String total = e.attr("style");
        String[] styleStr = total.split(";");

        for (String str : styleStr) {
            str = str.replace(" ", "");
            String[] one = str.split(":");
            if (one.length > 0) {
                if (one[1].contains("px")) {
                    one[1] = one[1].replace("px", "");
                }
                if ("color".equals(one[0])) {
                    one[1] = one[1].replace("#", "");
                }
                styleMap.put(one[0], one[1]);
            }
        }

        return styleMap;
    }

}

附:使用到的關鍵pom依賴

<!-- poi 相關 -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>4.1.1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>4.1.1</version>
    </dependency>

<!-- jsoup 解析html -->
    <dependency>
      <groupId>org.jsoup</groupId>
      <artifactId>jsoup</artifactId>
      <version>1.8.3</version>
    </dependency>

效果圖