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>

效果图

猜你喜欢

转载自www.cnblogs.com/hejjon/p/13381325.html