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(...        
该文章为易网时代-编程资源站会员专属文章,请先登录后再进行查看。