使用poi 生成 word文档,带表格 带图片

@RequestMapping(value="exportApplyForm")

    public void exportApplyForm(HttpServletResponse response,HttpServletRequest request,Long id) throws Exception { 

AdmissionTicket admissionTicket= admissionTicketRepository.findOne(id);

            Map<String, Object> params = new HashMap<String, Object>(); 


            params.put("${name}", admissionTicket.getSpecTionId().getName()); 

            params.put("${admissionTicket}",admissionTicket.getSpecTionId().getGender()); 

            params.put("${degreeEdu}",admissionTicket.getSpecTionId().getDegreeEdu()); 

            params.put("${identityId}",admissionTicket.getSpecTionId().getIdentityId());

            params.put("${organizationId}",admissionTicket.getSpecTionId().getOrganizationId().getName());

            params.put("${photo}",admissionTicket.getSpecTionId().getPhoto());

            String ss=request.getServletContext().getRealPath("demo/stas.docx");

            File file=new File(ss);

            XwpfTUtil xwpfTUtil = new XwpfTUtil(); 


            XWPFDocument doc; 

            InputStream is; 

            /*is = new FileInputStream(filePath);*/ 

            is =new FileInputStream(file);;      //本身就在编译路径下。。。。


            doc = new XWPFDocument(is); 


            xwpfTUtil.replaceInPara(doc, params); 

            //替换表格里面的变量 

            xwpfTUtil.replaceInTable(doc, params);

            OutputStream os = response.getOutputStream(); 


            response.setContentType("application/vnd.ms-excel"); 

            response.setHeader("Content-disposition","attachment;filename=测试.docx"); 

            doc.write(os); 


            xwpfTUtil.close(os); 

            xwpfTUtil.close(is); 


            os.flush(); 

            os.close(); 

        } 





/****************************************************************************************************************方法类**********************

package com.yuyang.sicm.service;


import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import org.apache.poi.util.Units;

import org.apache.poi.xwpf.usermodel.*;

import org.apache.xmlbeans.XmlCursor;

import org.junit.Test;

import sun.misc.BASE64Encoder;

import java.io.*; 

import java.util.HashMap; 

import java.util.Iterator; 

import java.util.List; 

import java.util.Map; 

import java.util.regex.Matcher; 

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest; 


public class XwpfTUtil { 


    /*String filePath = "/sta.docx";

    InputStream is;

    XWPFDocument doc;

    Map<String, Object> params = new HashMap<String, Object>();

    {

        params.put("${name}", "xxx");

        params.put("${sex}", "男");

        params.put("${political}", "共青团员");

        params.put("${place}", "sssss");

        params.put("${classes}", "3102");

        params.put("${id}", "213123123");

        params.put("${qq}", "213123");

        params.put("${tel}", "312313213");

        params.put("${oldJob}", "sadasd");

        params.put("${swap}", "是");

        params.put("${first}", "asdasd");

        params.put("${second}", "综合事务部");

        params.put("${award}", "asda");

        params.put("${achievement}", "完成科协网站的开发");

        params.put("${advice}", "没有建议");

        params.put("${attach}", "无");

        try {

            is = new FileInputStream(filePath);

            doc = new XWPFDocument(is);

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }*/ 



    /**

    * 用一个docx文档作为模板,然后替换其中的内容,再写入目标文档中。

    *

    * @throws Exception

    */ 

    /*@Test

    public void testTemplateWrite() throws Exception {

        //替换段落里面的变量

        this.replaceInPara(doc, params);

        //替换表格里面的变量

        this.replaceInTable(doc, params);

        OutputStream os = new FileOutputStream("D:\\sta1.docx");

        doc.write(os);

        this.close(os);

        this.close(is);

    }*/ 


    /*@Test

    public void myTest1() throws Exception {

        *//*Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();

        XWPFParagraph para;

        while (iterator.hasNext()) {

            para = iterator.next();

            List<XWPFRun> runs = para.getRuns();

            para.removeRun(0);

            para.insertNewRun(0).setText("hello");

        }

        OutputStream os = new FileOutputStream("D:\\sta1.docx");

        doc.write(os);

        this.close(os);

        this.close(is);*//*

        System.out.println(this.matcher("报告日期:${reportDate}").find());

    }*/ 


    /*@Test

    public void myReplaceInPara() {

//        Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();

//        XWPFParagraph para;

//        while (iterator.hasNext()) {

//            para = iterator.next();

//            List<XWPFRun> runs = para.getRuns();

//

//

//        }

        System.out.println('{'=='{');

    }*/ 


    /**

    * 替换段落里面的变量

    *

    * @param doc    要替换的文档

    * @param params 参数

    * @throws IOException

    * @throws FileNotFoundException

    * @throws InvalidFormatException

    */ 

    public void replaceInPara(XWPFDocument doc, Map<String, Object> params) throws InvalidFormatException, FileNotFoundException, IOException { 

        Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator(); 

        XWPFParagraph para; 

        while (iterator.hasNext()) { 

            para = iterator.next(); 

            this.replaceInPara(para, params); 

        } 

    } 


    /**

    * 替换段落里面的变量

    *

    * @param para  要替换的段落

    * @param params 参数

    * @throws IOException

    * @throws FileNotFoundException

    * @throws InvalidFormatException

    */ 

    public void replaceInPara(XWPFParagraph para, Map<String, Object> params) throws InvalidFormatException, FileNotFoundException, IOException { 

        List<XWPFRun> runs; 

        Matcher matcher; 

        if (this.matcher(para.getParagraphText()).find()) { 

            runs = para.getRuns(); 


            int start = -1; 

            int end = -1; 

            String str = ""; 

            for (int i = 0; i < runs.size(); i++) { 

                XWPFRun run = runs.get(i); 

                String runText = run.toString(); 

                System.out.println("------>>>>>>>>>" + runText); 

                if ('$' == runText.charAt(0)&&'{' == runText.charAt(1)) { 

                    start = i; 

                } 

                if ((start != -1)) { 

                    str += runText; 

                } 

                if ('}' == runText.charAt(runText.length() - 1)) { 

                    if (start != -1) { 

                        end = i; 

                        break; 

                    } 

                } 

            } 

            System.out.println("start--->"+start); 

            System.out.println("end--->"+end); 


            System.out.println("str---->>>" + str); 


            for (int i = start; i <= end; i++) { 

                para.removeRun(i); 

                i--; 

                end--; 

                System.out.println("remove i="+i); 

            } 


            for (String key : params.keySet()) { 

                if (str.equals(key)) {

                if(str.equals("${photo}")) {

                para.createRun().addPicture(new FileInputStream(new File("F:/ceshi.PNG")), Document.PICTURE_TYPE_PNG, "测试",  Units.toEMU(200), Units.toEMU(200));

                break; 

                }

                    para.createRun().setText((String) params.get(key)); 

                    break; 

                } 

            } 



        } 

    } 


    /**

    * 替换表格里面的变量

    *

    * @param doc    要替换的文档

    * @param params 参数

    * @throws IOException

    * @throws FileNotFoundException

    * @throws InvalidFormatException

    */ 

    public void replaceInTable(XWPFDocument doc, Map<String, Object> params) throws InvalidFormatException, FileNotFoundException, IOException { 

        Iterator<XWPFTable> iterator = doc.getTablesIterator(); 

        XWPFTable table; 

        List<XWPFTableRow> rows; 

        List<XWPFTableCell> cells; 

        List<XWPFParagraph> paras; 

        while (iterator.hasNext()) { 

            table = iterator.next(); 

            rows = table.getRows(); 

            for (XWPFTableRow row : rows) { 

                cells = row.getTableCells(); 

                for (XWPFTableCell cell : cells) { 

                    paras = cell.getParagraphs(); 

                    for (XWPFParagraph para : paras) { 

                        this.replaceInPara(para, params); 

                    } 

                } 

            } 

        } 

    } 


/*   

    public void replacePhoto(XWPFDocument xwpfDocument, Map<String, Object> params) throws InvalidFormatException, FileNotFoundException, IOException {

    List<XWPFParagraph> xwpfParas=xwpfDocument.getParagraphs();//获取一格里的内容  list

    for(int i=0;i<xwpfParas.size();i++){

        XWPFParagraph xwpfParagraph = xwpfParas.get(i);

        String text=xwpfParagraph.getText();//获取单元格内的内容


        if(text.equals("${mark_newPicture}")) {

          XmlCursor cursor = xwpfParagraph .getCTP().newCursor();

              XWPFParagraph newPara = xwpfDocument.insertNewParagraph(cursor);

              newPara.setAlignment(ParagraphAlignment.CENTER);//居中

              XWPFRun newParaRun = newPara.createRun();

              newParaRun.addPicture(new FileInputStream("demo/juhua.jpg"),XWPFDocument.PICTURE_TYPE_PNG,"bus.png,",Units.toEMU(200), Units.toEMU(200));

              xwpfDocument.removeBodyElement(xwpfDocument.getPosOfParagraph(xwpfParagraph));

        }

    }

}

    *//**

    * 取得全部段落

    * @param xwpfDocument

    * @param params

    * @throws InvalidFormatException

    * @throws FileNotFoundException

    * @throws IOException

    *//*


    public void replaceInPhoto(XWPFDocument doc, Map<String, Object> params) throws InvalidFormatException, FileNotFoundException, IOException { 

        Iterator<XWPFTable> iterator = doc.getTablesIterator(); 

        XWPFTable table; 

        List<XWPFTableRow> rows; 

        List<XWPFTableCell> cells; 

        List<XWPFParagraph> paras; 

        while (iterator.hasNext()) { 

            table = iterator.next(); 

            rows = table.getRows(); 

            for (XWPFTableRow row : rows) { 

                cells = row.getTableCells(); 

                for (XWPFTableCell cell : cells) { 

                    paras = cell.getParagraphs(); 

                    for (XWPFParagraph para : paras) { 

                        this.replaceInPhoto(para, params); 

                    } 

                } 

            } 

        } 

    } 

    *//**

    *

    * @param para  段落

    * @param params

    * @throws IOException

    * @throws FileNotFoundException

    * @throws InvalidFormatException

    *//*


    public void replaceInPhoto(XWPFParagraph para, Map<String, Object> params) throws InvalidFormatException, FileNotFoundException, IOException { 

        List<XWPFRun> runs; 

        Matcher matcher; 

        if (this.matcher(para.getParagraphText()).find()) { 

            runs = para.getRuns(); 


            int start = -1; 

            int end = -1; 

            String str = ""; 

            for (int i = 0; i < runs.size(); i++) { 

                XWPFRun run = runs.get(i); 

                String runText = run.toString(); 

                System.out.println("------>>>>>>>>>" + runText); 

                if ('$' == runText.charAt(0)&&'{' == runText.charAt(1)) { 

                    start = i; 

                } 

                if ((start != -1)) { 

                    str += runText; 

                } 

                if ('}' == runText.charAt(runText.length() - 1)) { 

                    if (start != -1) { 

                        end = i; 

                        break; 

                    } 

                } 

            } 

            System.out.println("start--->"+start); 

            System.out.println("end--->"+end); 


            System.out.println("str---->>>" + str); 


            for (int i = start; i <= end; i++) { 

                para.removeRun(i); 

                i--; 

                end--; 

                System.out.println("remove i="+i); 

            } 


            for (String key : params.keySet()) { 

                if(str.equals("${photo}")) {

                para.createRun().addPicture(new FileInputStream(new File("demo/ceshi.PNG")), Document.PICTURE_TYPE_PNG, "测试",  Units.toEMU(200), Units.toEMU(200));


                break; 

                }

            } 



        } 

    } */


    /**

    * 正则匹配字符串

    *

    * @param str

    * @return

    */ 

    private Matcher matcher(String str) { 

        Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE); 

        Matcher matcher = pattern.matcher(str); 

        return matcher; 

    } 


    /**

    * 关闭输入流

    *

    * @param is

    */ 

    public void close(InputStream is) { 

        if (is != null) { 

            try { 

                is.close(); 

            } catch (IOException e) { 

                e.printStackTrace(); 

            } 

        } 

    } 


    /**

    * 关闭输出流

    *

    * @param os

    */ 

    public void close(OutputStream os) { 

        if (os != null) { 

            try { 

                os.close(); 

            } catch (IOException e) { 

                e.printStackTrace(); 

            } 

        } 

    }


    private String getImageStr(String path) {

    String imgFile = path;

    InputStream in = null;

    byte[] data = null;

    try {

    in = new FileInputStream(imgFile);

    data = new byte[in.available()];

    in.read(data);

    in.close();

    } catch (IOException e) {

    e.printStackTrace();

    }

    BASE64Encoder encoder = new BASE64Encoder();

    return encoder.encode(data);

    }


}






参考文章 https://hacpai.com/article/1504680819318#toc_h3_0

https://www.jianshu.com/p/de58ab550157

https://blog.csdn.net/mate_ge/article/details/50812831

https://blog.csdn.net/java_xuetu/article/details/79540622


Can't open the specified file: 'demo/demo.docx'

在导出图片的时候导出的图片不显示,  最后查得,这个是版本的问题,  最后换成3.16的版本就好

<dependency>

            <groupId>org.apache.poi</groupId> 

            <artifactId>poi</artifactId> 

            <version>3.16-beta2</version> 

            <type>jar</type> 

            <scope>compile</scope> 

        </dependency> 

        <dependency> 

            <groupId>org.apache.poi</groupId> 

            <artifactId>poi-ooxml</artifactId> 

            <version>3.16-beta2</version> 

            <type>jar</type> 

        </dependency> 

        <dependency> 

            <groupId>org.apache.poi</groupId> 

            <artifactId>poi-ooxml-schemas</artifactId> 

            <version>3.16-beta2</version> 

            <type>jar</type> 

            <scope>compile</scope> 

        </dependency> 

        <dependency> 

            <groupId>org.apache.poi</groupId> 

            <artifactId>poi-scratchpad</artifactId> 

            <version>3.0.2-FINAL</version> 

        </dependency> 

</dependencies>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,233评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,013评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,030评论 0 241
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,827评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,221评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,542评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,814评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,513评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,225评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,497评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,998评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,342评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,986评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,812评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,560评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,461评论 2 266

推荐阅读更多精彩内容

  • 一、 1、请用Java写一个冒泡排序方法 【参考答案】 public static void Bubble(int...
    独云阅读 1,231评论 0 6
  • 项目要求用json提交参数,以前在网上找的别的大神(忘了是谁)封装的NetUtils工具不适应了,在网上也没找到适...
    微暖_440e阅读 1,061评论 0 0
  • DiskLurCache 使用教程 源码解析 使用 打开缓存 打开缓存函数public static DiskLr...
    super小立立阅读 875评论 1 1
  • Q3思考【角度】围绕着减少线上bug数,保证产品质量,提高团队工作效率思考,存在哪些问题。 【流程】发现问题---...
    心无旁骛_阅读 191评论 0 0
  • 大自然就是最典型的统合综效的结果。就是树木、微生物、动物等等,发挥最好的一个作用。 那我们...
    修行者张易阅读 738评论 0 0