Welcome

首页 / 软件开发 / JAVA / Java使用easypoi输出文本以及图片到word文档

Java使用easypoi输出文本以及图片到word文档  

引入依赖

    org.apache.poi
    poi-ooxml
    5.0.0

示例代码
package cn.com.weisoft;

import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) {
        //创建一个document对象,相当于新建一个word文档(后缀名为.docx)。
        XWPFDocument document = new XWPFDocument();
        //创建一个段落对象。
        XWPFParagraph paragraph = document.createParagraph();
        //创建一个run。run具体是什么,我也不知道。但是run是这里面的最小单元了。
        XWPFRun run = paragraph.createRun();
        //插入图片
        try {
            String imgpath = "/Users/admin/Downloads/6.jpg";
            for(int i=1;i<10;i++) {
                int[] wh = getImageWidthAndHeight(imgpath);
                int[] afwh = transWidthAndHeight(wh);
                run.setText(i+"、Hello World");
                run.addBreak();
                run.setText("https://www.escdns.com");
                run.addBreak();
                run.addPicture(Files.newInputStream(Paths.get(imgpath)),
                        XWPFDocument.PICTURE_TYPE_PNG,
                        imgpath,
                        Units.toEMU(afwh[0]),
                        Units.toEMU(afwh[1]));
            }
            //创建一个输出流 即是该文档的保存位置
            OutputStream outputStream = Files.newOutputStream(Paths.get("/Users/admin/Downloads/1.docx"));
            document.write(outputStream);
            outputStream.close();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
    //取得图片宽度和高度
    public static int[] getImageWidthAndHeight(String imgPath) {
        int[] wh = new int[]{0, 0};
        if (imgPath.isEmpty()) {
            return wh;
        }
        // 读取图片文件
        try {
            File imageFile = new File(imgPath);
            BufferedImage bufferedImage = ImageIO.read(imageFile);
            if (bufferedImage != null) {
                wh[0] = bufferedImage.getWidth();
                wh[1] = bufferedImage.getHeight();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return wh;
    }
    //等比缩放
    public static int[] transWidthAndHeight(int[] wh) {
        int w = 410;
        int h = 0;
        int rh = w * wh[1] / wh[0];
        int[] r = new int[]{w, rh};
        return r;
    }
}