欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

poi-word导出,导出多图片到word

程序员文章站 2022-07-02 14:12:23
一、添加依赖 二、工具类 ......

一、添加依赖

        <dependency>
            <groupid>org.apache.poi</groupid>
            <artifactid>poi-scratchpad</artifactid>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupid>org.apache.poi</groupid>
            <artifactid>poi-ooxml</artifactid>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupid>com.deepoove</groupid>
            <artifactid>poi-tl</artifactid>
            <version>1.0.0</version>
        </dependency>

  

二、工具类

import java.awt.image.bufferedimage;
import java.io.*;
import java.text.simpledateformat;
import java.util.*;
import com.deepoove.poi.xwpftemplate;
import com.deepoove.poi.data.picturerenderdata;
import com.hdvon.nmp.vcase.config.appconfig;
import com.hdvon.nmp.vcase.helper.springhelper;
import lombok.extern.slf4j.slf4j;
import org.apache.commons.lang3.stringutils;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.util.filecopyutils;

import javax.imageio.imageio;

/**
 * 适用于word 2007
 * poi 版本 3.7
 */
@slf4j
public class wordhelper {

    /***
     * 写入书签内容、图片t
     * @param oldfilename 旧的文件名
     * @param filepath 模板文件路径
     * @param map 指定写入书签参数
     */
    public string export(string oldfilename,string filepath, map<string, object> oldmap){
        appconfig appconfig = springhelper.getbean(appconfig.class);
        string folder=appconfig.getbasepath()+appconfig.getwordpath();
        try {
            map<string, object> map=new hashmap<>();
            for (string key:oldmap.keyset()){
                map.put("${"+key+"}",oldmap.get(key));
            }
            if(stringutils.isblank(folder))return "";
            string newfilefolder=folder+new simpledateformat("yyyy-mm-dd").format(new date());
            file newfile=new file(newfilefolder);
            if(!newfile.exists()){
                newfile.mkdir();
            }
            string filename=new simpledateformat("yyyy-mm-dd").format(new date())+"\\"+oldfilename;
            file outfile=new file(folder+filename);
            //复制一份模板
            string copypath=folder+new simpledateformat("yyyy-mm-dd").format(new date())+"\\"+"template.docx";
            file copyfile=new file(copypath);
            filecopyutils.copy(new file(filepath),copyfile);
            //写入文字到doc
            outputstream outputstream = null;
            outputstream = new fileoutputstream(outfile);
            xwpfdocument doc=wordutil.generateword(map,copypath);
            doc.write(outputstream);
            outputstream.flush();
            outputstream.close();
            doc.close();
            //写入图片到doc
            string picurl = (string)map.get("${picurl}");
            string[] urls = picurl.split(";");
            int size=urls.length;
            fileinputstream inputstream=new fileinputstream(outfile);
            xwpfdocument doc1=new xwpfdocument(inputstream);
            outputstream = new fileoutputstream(outfile);
            xwpfparagraph lastparagraph = doc1.getlastparagraph();
            for(int i=1;i<=size;i++){
                xwpfrun run = lastparagraph.createrun();
                run.settext("{{@localhostpicture"+i+"}}");
                lastparagraph.addrun(run);

            }
            doc1.write(outputstream);
            inputstream.close();
            outputstream.close();
            doc1.close();


           map<string,object> datas=new hashmap<string,object>();
           file imgfile=null;
           fileinputstream imginputstream=null;
           bufferedimage image=null;
            for(int i=0;i< urls.length;i++){
                string url=urls[i];
                url=appconfig.getbasepath()+url;
                imgfile=new file(url);
                if(!imgfile.exists()) continue;
                imginputstream=new fileinputstream(imgfile);
                image= imageio.read(imginputstream);
                if(stringutils.isnotblank(url)) {
                    datas.put("localhostpicture" + (i + 1), new picturerenderdata(image.getwidth(), image.getheight(), url));
                }
            }

            xwpftemplate template=xwpftemplate.compile(outfile).render(datas);
            fileoutputstream out1=new fileoutputstream(outfile);
            template.write(out1);
            out1.flush();
            out1.close();
            template.close();
            imginputstream.close();
        }catch (exception e){
            e.printstacktrace();
        }
        return appconfig.getwordpath()+new simpledateformat("yyyy-mm-dd").format(new date())+"/"+oldfilename;
    }
}

  

import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.ioexception;
import java.io.inputstream;
import java.util.iterator;
import java.util.list;
import java.util.map;
import java.util.map.entry;
import org.apache.poi.poixmldocument;
import org.apache.poi.openxml4j.exceptions.invalidformatexception;
import org.apache.poi.openxml4j.opc.opcpackage;
import org.apache.poi.xwpf.usermodel.xwpfdocument;
import org.apache.poi.xwpf.usermodel.xwpfparagraph;
import org.apache.poi.xwpf.usermodel.xwpfrun;
import org.apache.poi.xwpf.usermodel.xwpftable;
import org.apache.poi.xwpf.usermodel.xwpftablecell;
import org.apache.poi.xwpf.usermodel.xwpftablerow;
import org.apache.xmlbeans.xmlexception;
import org.apache.xmlbeans.xmltoken;
import org.openxmlformats.schemas.drawingml.x2006.main.ctnonvisualdrawingprops;
import org.openxmlformats.schemas.drawingml.x2006.main.ctpositivesize2d;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingdrawing.ctinline;

/**
 * 适用于word 2007
 * poi 版本 3.7
 */
public class wordutil {

    /**
     * 根据指定的参数值、模板,生成 word 文档
     *
     * @param param    需要替换的变量
     * @param template 模板
     */
    public static xwpfdocument generateword(map<string, object> param, string template) {
        xwpfdocument doc = null;
        try {
            opcpackage pack = poixmldocument.openpackage(template);
            doc = new customxwpfdocument(pack);
            if (param != null && param.size() > 0) {

                //处理段落
                list<xwpfparagraph> paragraphlist = doc.getparagraphs();
                processparagraphs(paragraphlist, param, doc);

                //处理表格
                iterator<xwpftable> it = doc.gettablesiterator();
                while (it.hasnext()) {
                    xwpftable table = it.next();
                    list<xwpftablerow> rows = table.getrows();
                    for (xwpftablerow row : rows) {
                        list<xwpftablecell> cells = row.gettablecells();
                        for (xwpftablecell cell : cells) {
                            list<xwpfparagraph> paragraphlisttable = cell.getparagraphs();
                            processparagraphs(paragraphlisttable, param, doc);
                        }
                    }
                }
            }
        } catch (exception e) {
            e.printstacktrace();
        }
        return doc;
    }

    /**
     * 处理段落
     *
     * @param paragraphlist
     * @throws filenotfoundexception
     * @throws invalidformatexception
     */
    public static void processparagraphs(list<xwpfparagraph> paragraphlist, map<string, object> param, xwpfdocument doc) throws invalidformatexception, filenotfoundexception {
        if (paragraphlist != null && paragraphlist.size() > 0) {
            for (xwpfparagraph paragraph : paragraphlist) {
                list<xwpfrun> runs = paragraph.getruns();
                for (xwpfrun run : runs) {
                    string text = run.gettext(0);
                    if (text != null) {
                        boolean issettext = false;
                        for (entry<string, object> entry : param.entryset()) {
                            string key = entry.getkey();
                            if (text.indexof(key) != -1) {
                                issettext = true;
                                object value = entry.getvalue();
                                if (value instanceof object) {//文本替换
                                    text = text.replace(key, value.tostring());
                                } else if (value instanceof map) {    //图片替换
                                    text = text.replace(key, "");
                                    map pic = (map) value;
                                    int width = integer.parseint(pic.get("width").tostring());
                                    int height = integer.parseint(pic.get("height").tostring());
                                    int pictype = getpicturetype(pic.get("type").tostring());
                                    string bytearray = (string) pic.get("content");


                                    //bytearrayinputstream byteinputstream = new bytearrayinputstream(bytearray);

                                    //int ind = doc.getallpictures().size() - 1;
                                    //doc.createpicture(ind, width , height,paragraph);
                                    ctinline inline = run.getctr().addnewdrawing().addnewinline();
                                    insertpicture(doc, bytearray, inline, width, height);

                                }
                            }
                        }
                        if (issettext) {
                            run.settext(text, 0);
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据图片类型,取得对应的图片类型代码
     *
     * @param pictype
     * @return int
     */
    private static int getpicturetype(string pictype) {
        int res = customxwpfdocument.picture_type_pict;
        if (pictype != null) {
            if (pictype.equalsignorecase("png")) {
                res = customxwpfdocument.picture_type_png;
            } else if (pictype.equalsignorecase("dib")) {
                res = customxwpfdocument.picture_type_dib;
            } else if (pictype.equalsignorecase("emf")) {
                res = customxwpfdocument.picture_type_emf;
            } else if (pictype.equalsignorecase("jpg") || pictype.equalsignorecase("jpeg")) {
                res = customxwpfdocument.picture_type_jpeg;
            } else if (pictype.equalsignorecase("wmf")) {
                res = customxwpfdocument.picture_type_wmf;
            }
        }
        return res;
    }

    /**
     * 将输入流中的数据写入字节数组
     *
     * @param in
     * @return
     */
    public static byte[] inputstream2bytearray(inputstream in, boolean isclose) {
        byte[] bytearray = null;
        try {
            int total = in.available();
            bytearray = new byte[total];
            in.read(bytearray);
        } catch (ioexception e) {
            e.printstacktrace();
        } finally {
            if (isclose) {
                try {
                    in.close();
                } catch (exception e2) {
                    system.out.println("关闭流失败");
                }
            }
        }
        return bytearray;
    }

    /**
     * insert picture
     *
     * @param document
     * @param filepath
     * @param inline
     * @param width
     * @param height
     * @throws invalidformatexception
     * @throws filenotfoundexception
     */
    private static void insertpicture(xwpfdocument document, string filepath,
                                      ctinline inline, int width,
                                      int height) throws invalidformatexception,
            filenotfoundexception {
        document.addpicturedata(new fileinputstream(filepath), xwpfdocument.picture_type_png);
        int id = document.getallpictures().size() - 1;
        final int emu = 9525;
        width *= emu;
        height *= emu;
        string blipid =
                document.getallpictures().get(id).getpackagerelationship().getid();
        string picxml = getpicxml(blipid, width, height);
        xmltoken xmltoken = null;
        try {
            xmltoken = xmltoken.factory.parse(picxml);
        } catch (xmlexception xe) {
            xe.printstacktrace();
        }
        inline.set(xmltoken);
        inline.setdistt(0);
        inline.setdistb(0);
        inline.setdistl(0);
        inline.setdistr(0);
        ctpositivesize2d extent = inline.addnewextent();
        extent.setcx(width);
        extent.setcy(height);
        ctnonvisualdrawingprops docpr = inline.addnewdocpr();
        docpr.setid(id);
        docpr.setname("img_" + id);
        docpr.setdescr("img_" + id);
    }

    /**
     * get the xml of the picture
     *
     * @param blipid
     * @param width
     * @param height
     * @return
     */
    private static string getpicxml(string blipid, int width, int height) {
        string picxml =
                "" + "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" +
                        "   <a:graphicdata uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
                        "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
                        "         <pic:nvpicpr>" + "            <pic:cnvpr id=\"" + 0 +
                        "\" name=\"generated\"/>" + "            <pic:cnvpicpr/>" +
                        "         </pic:nvpicpr>" + "         <pic:blipfill>" +
                        "            <a:blip r:embed=\"" + blipid +
                        "\" xmlns:r=\"http://schemas.openxmlformats.org/officedocument/2006/relationships\"/>" +
                        "            <a:stretch>" + "               <a:fillrect/>" +
                        "            </a:stretch>" + "         </pic:blipfill>" +
                        "         <pic:sppr>" + "            <a:xfrm>" +
                        "               <a:off x=\"0\" y=\"0\"/>" +
                        "               <a:ext cx=\"" + width + "\" cy=\"" + height +
                        "\"/>" + "            </a:xfrm>" +
                        "            <a:prstgeom prst=\"rect\">" +
                        "               <a:avlst/>" + "            </a:prstgeom>" +
                        "         </pic:sppr>" + "      </pic:pic>" +
                        "   </a:graphicdata>" + "</a:graphic>";
        return picxml;
    }
}