java 动态导出word文档 文档合并分页,浏览器下载,生成,动态表格,加图片

1.官方文档 Poi-tl Documentationjava 动态导出word文档 文档合并分页,浏览器下载,生成,动态表格,加图片_第1张图片

word 模板 准备 .docx 文件

java 动态导出word文档 文档合并分页,浏览器下载,生成,动态表格,加图片_第2张图片

再准备一张图片 一起放到项目的resources目录下 

java 动态导出word文档 文档合并分页,浏览器下载,生成,动态表格,加图片_第3张图片

impl层 第一个word文档,第二第三个与第一个相差不大

java 动态导出word文档 文档合并分页,浏览器下载,生成,动态表格,加图片_第4张图片

java 动态导出word文档 文档合并分页,浏览器下载,生成,动态表格,加图片_第5张图片 java 动态导出word文档 文档合并分页,浏览器下载,生成,动态表格,加图片_第6张图片

 官网中文本设置样式

java 动态导出word文档 文档合并分页,浏览器下载,生成,动态表格,加图片_第7张图片

 java 动态导出word文档 文档合并分页,浏览器下载,生成,动态表格,加图片_第8张图片

传入图片

java 动态导出word文档 文档合并分页,浏览器下载,生成,动态表格,加图片_第9张图片

java 动态导出word文档 文档合并分页,浏览器下载,生成,动态表格,加图片_第10张图片 controller层

java 动态导出word文档 文档合并分页,浏览器下载,生成,动态表格,加图片_第11张图片

java 动态导出word文档 文档合并分页,浏览器下载,生成,动态表格,加图片_第12张图片

java 动态导出word文档 文档合并分页,浏览器下载,生成,动态表格,加图片_第13张图片

java 动态导出word文档 文档合并分页,浏览器下载,生成,动态表格,加图片_第14张图片

代码:

引入依赖,注意版本冲突


    org.apache.poi
    poi
    4.1.2


    org.apache.poi
    poi-ooxml
    4.1.2



    org.apache.poi
    poi-ooxml-schemas
    4.1.2



    com.deepoove
    poi-tl
    1.10.0

 Controller 层代码

package com.example.demo.controller;

import com.deepoove.poi.util.PoitlIOUtils;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import com.example.demo.contain.CommonConstant;
import com.example.demo.service.FileServcie;
import com.example.demo.service.LogReportService;
import com.example.demo.util.Base64Utile;
import com.example.demo.util.FileDeleteUtile;
import fr.opensagres.xdocreport.core.XDocReportException;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping(value = "/local5")
public class LogController {

    @Resource
    private LogReportService logReportService;

    @Resource
    private FileServcie fileServcie;

    @GetMapping
    public void exportWord1(HttpServletResponse response) throws IOException, XDocReportException, Exception {

        String path1 = this.getClass().getClassLoader().getResource("2020101814395601.png").getPath();
        String imgBase = Base64Utile.getImgBase(path1);
        //日志数量统计
        logReportService.opLogDocx(imgBase,response);

        //系统日志统计
        logReportService.systemLogResDocx(imgBase,response);

        //监控日志统计
        logReportService.monitorLogResLogDocx(imgBase,response);

        //系统日志访问用户top10统计
        logReportService.loginDocx(imgBase,response);

        String oplogPath =fileServcie.docxPath()+ CommonConstant.SEPARATOR +"oplog.docx";
        String systemLogResPath =fileServcie.docxPath()+ CommonConstant.SEPARATOR +"systemLogRes.docx";
        String monitorLogResPath =fileServcie.docxPath()+ CommonConstant.SEPARATOR +"monitorLogRes.docx";
        String loginPath =fileServcie.docxPath()+ CommonConstant.SEPARATOR +"login.docx";


        NiceXWPFDocument oplog = new NiceXWPFDocument(new FileInputStream(oplogPath));
        NiceXWPFDocument systemLogRes = new NiceXWPFDocument(new FileInputStream(systemLogResPath));
        NiceXWPFDocument monitorLogRes = new NiceXWPFDocument(new FileInputStream(monitorLogResPath));
        NiceXWPFDocument login = new NiceXWPFDocument(new FileInputStream(loginPath));

        //设置内容不合并
        XWPFParagraph paragraph = oplog.createParagraph();
        paragraph.setPageBreak(true);

        XWPFParagraph paragraph1 = systemLogRes.createParagraph();
        paragraph1.setPageBreak(true);

        XWPFParagraph paragraph2 = monitorLogRes.createParagraph();
        paragraph2.setPageBreak(true);



        //开始合并文件
        NiceXWPFDocument merge = oplog.merge(systemLogRes).merge(monitorLogRes).merge(login);

        //日志文件名
        Date date = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = ft.format(date);
        String[] split = format.split(" ");
        String[] time = split[0].split("-");
        String[] timeDate = split[1].split(":");
        String fileName ="日志报表-" + time[0]+time[1]+time[2]+timeDate[0]+timeDate[1]+timeDate[2]+ ".docx";
        //生成临时文件存放地址
        String temDir=fileServcie.docxPath();
        FileOutputStream fos = new FileOutputStream(temDir+ CommonConstant.SEPARATOR +fileName);
        merge.write(fos);
        String path = fileServcie.docxPath()+CommonConstant.SEPARATOR+fileName;


        fileServcie.handleDownloadFile(path, response, fileName);

        PoitlIOUtils.closeQuietlyMulti(merge,oplog,systemLogRes,monitorLogRes,login, fos);


        FileDeleteUtile.deleteFile(new File(fileServcie.docxPath()));

    }


}

Service

package com.example.demo.service;

import fr.opensagres.xdocreport.core.XDocReportException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public interface LogReportService {
    /**
     * 系统日志统计
     * @param response
     * @throws IOException
     * @throws XDocReportException
     */
    void systemLogResDocx(String base64,HttpServletResponse response)throws IOException, XDocReportException;

    /**
     * 监控日志统计
     * @param response
     * @throws IOException
     * @throws XDocReportException
     */
    void monitorLogResLogDocx(String base64,HttpServletResponse response)throws IOException, XDocReportException;

    /**
     *日志数量统计
     * @param response
     * @throws IOException
     * @throws XDocReportException
     */
    void opLogDocx(String base64,HttpServletResponse response)throws IOException, XDocReportException;

    /**
     *系统日志访问用户top10统计
     * @param response
     * @throws IOException
     * @throws XDocReportException
     */
    void loginDocx(String base64,HttpServletResponse response)throws IOException, XDocReportException;
}

impl

package com.example.demo.impl;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.*;
import com.deepoove.poi.util.PoitlIOUtils;
import com.example.demo.contain.CommonConstant;
import com.example.demo.service.FileServcie;
import com.example.demo.service.LogReportService;
import fr.opensagres.xdocreport.core.XDocReportException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LogReportServiceImpl implements LogReportService {

    @Resource
    private FileServcie fileServcie;


    @Override
    public void opLogDocx(String base64,HttpServletResponse response) throws IOException, XDocReportException {
        //创建XWPFTemplate对象,并设置读取模板路径和要渲染的数据
        String path = this.getClass().getClassLoader().getResource("报表公用模板.docx").getPath();
        String filePath = URLDecoder.decode(path, "UTF-8");//如果路径中带有中文会被URLEncoder,因此这里需要解码

        //目前图片在resource目录下
        String path1 = this.getClass().getClassLoader().getResource("2020101814395601.png").getPath();

        //主题
        HashMap theme = new HashMap() {{
            put("theme",Texts.of("日志报表").fontSize(22).bold().create());
        }};

        //标题
        HashMap title = new HashMap() {{
            put("title",Texts.of("1.日志数量统计").fontSize(12).bold().create());
        }};

        //图片
        HashMap value = new HashMap() {{
            put("value", Pictures.ofBase64(base64, PictureType.PNG).center().create());
        }};
        //表格
        HashMap table = new HashMap() {{
            // 第0行居中且背景为蓝色的表格
            RowRenderData row0 = Rows.of("序号", "日期", "系统日志", "监控日志", "主机日志").center().create();
            put("table", Tables.create(row0));
            String id;

            //结果集
            List renderDataList = new ArrayList<>();
            renderDataList.add(row0);
            for (int i = 0; i < 56; i++) {
                id = String.valueOf(i+1);
                RowRenderData rowi = Rows.create(id, "2022", "100", "150", null);
                renderDataList.add(rowi);
            }
            //list转数组
            RowRenderData[] rowRenderDatas = renderDataList.toArray(new RowRenderData[renderDataList.size()]);

            put("table", Tables.create(rowRenderDatas));
        }};

        List> listMap = new ArrayList<>();
        listMap.add(theme);
        listMap.add(title);
        listMap.add(value);
        listMap.add(table);
        Map map = new HashMap<>();
        map.put("sections",listMap);
        XWPFTemplate template = XWPFTemplate.compile(filePath).render(map);

        //=================生成文件保存在本地文件目录下=================
        //生成临时文件存放地址
        String temDir=fileServcie.docxPath();
        //文件名  带后缀
        String fileName = "oplog.docx";
        FileOutputStream fos = new FileOutputStream(temDir+ CommonConstant.SEPARATOR +fileName);
        template.write(fos);
        PoitlIOUtils.closeQuietlyMulti(template, fos);
    }
    @Override
    public void systemLogResDocx(String base64,HttpServletResponse response) throws IOException, XDocReportException {
        //创建XWPFTemplate对象,并设置读取模板路径和要渲染的数据
        String path = this.getClass().getClassLoader().getResource("报表公用模板.docx").getPath();
        String filePath = URLDecoder.decode(path, "UTF-8");//如果路径中带有中文会被URLEncoder,因此这里需要解码

        //目前图片在resource目录下
        String path1 = this.getClass().getClassLoader().getResource("2020101814395601.png").getPath();


        //标题
        HashMap title = new HashMap() {{
            put("title",Texts.of("2.系统日志操作结果统计").fontSize(12).bold().create());
        }};

        //图片
        HashMap value = new HashMap() {{
            put("value", Pictures.ofBase64(base64, PictureType.PNG).center().create());
        }};

        //表格
        HashMap table = new HashMap() {{
            // 第0行居中且背景为蓝色的表格
            RowRenderData row0 = Rows.of("序号", "日期", "成功", "失败", "异常", "成功率%").center().create();
            put("table", Tables.create(row0));
            String id;

            //结果集
            List renderDataList = new ArrayList<>();
            renderDataList.add(row0);
            for (int i = 0; i < 6; i++) {
                id = String.valueOf(i+1);
                RowRenderData rowi = Rows.create(id, "2022", "是", null,null, "100%");
                renderDataList.add(rowi);
            }
            //list转数组
            RowRenderData[] rowRenderDatas = renderDataList.toArray(new RowRenderData[renderDataList.size()]);

            put("table", Tables.create(rowRenderDatas));
        }};

        List> listMap = new ArrayList<>();
//        listMap.add(theme);
        listMap.add(title);
        listMap.add(value);
        listMap.add(table);
        Map map = new HashMap<>();
        map.put("sections",listMap);
        XWPFTemplate template = XWPFTemplate.compile(filePath).render(map);

        //=================生成文件保存在本地文件目录下=================
        //生成临时文件存放地址
        String temDir=fileServcie.docxPath();
        //文件名  带后缀
        String fileName = "systemLogRes.docx";
        FileOutputStream fos = new FileOutputStream(temDir+ CommonConstant.SEPARATOR +fileName);
        template.write(fos);
        PoitlIOUtils.closeQuietlyMulti(template, fos);
    }

    @Override
    public void monitorLogResLogDocx(String base64,HttpServletResponse response) throws IOException, XDocReportException {
        //创建XWPFTemplate对象,并设置读取模板路径和要渲染的数据
        String path = this.getClass().getClassLoader().getResource("报表公用模板.docx").getPath();
        String filePath = URLDecoder.decode(path, "UTF-8");//如果路径中带有中文会被URLEncoder,因此这里需要解码

        //目前图片在resource目录下
        String path1 = this.getClass().getClassLoader().getResource("2020101814395601.png").getPath();



        //标题
        HashMap title = new HashMap() {{
            put("title",Texts.of("3.监控日志操作结果统计").fontSize(12).bold().create());
        }};

        //图片
        HashMap value = new HashMap() {{
            put("value", Pictures.ofBase64(base64, PictureType.PNG).center().create());
        }};

        //表格
        HashMap table = new HashMap() {{
            // 第0行居中且背景为蓝色的表格
            RowRenderData row0 = Rows.of("序号", "日期", "成功", "失败", "异常", "成功率%").center().create();
            put("table", Tables.create(row0));
            String id;

            //结果集
            List renderDataList = new ArrayList<>();
            renderDataList.add(row0);
            for (int i = 0; i < 6; i++) {
                id = String.valueOf(i+1);
                RowRenderData rowi = Rows.create(id, "2022", "是", null,null, "100%");
                renderDataList.add(rowi);
            }
            //list转数组
            RowRenderData[] rowRenderDatas = renderDataList.toArray(new RowRenderData[renderDataList.size()]);

            put("table", Tables.create(rowRenderDatas));
        }};

        List> listMap = new ArrayList<>();
//        listMap.add(theme);
        listMap.add(title);
        listMap.add(value);
        listMap.add(table);
        Map map = new HashMap<>();
        map.put("sections",listMap);
        XWPFTemplate template = XWPFTemplate.compile(filePath).render(map);

        //=================生成文件保存在本地文件目录下=================
        //生成临时文件存放地址
        String temDir=fileServcie.docxPath();
        //文件名  带后缀
        String fileName = "monitorLogRes.docx";
        FileOutputStream fos = new FileOutputStream(temDir+ CommonConstant.SEPARATOR +fileName);
        template.write(fos);
        PoitlIOUtils.closeQuietlyMulti(template, fos);
    }



    @Override
    public void loginDocx(String base64,HttpServletResponse response) throws IOException, XDocReportException {
        //创建XWPFTemplate对象,并设置读取模板路径和要渲染的数据
        String path = this.getClass().getClassLoader().getResource("报表公用模板.docx").getPath();
        String filePath = URLDecoder.decode(path, "UTF-8");//如果路径中带有中文会被URLEncoder,因此这里需要解码

        //目前图片在resource目录下
        String path1 = this.getClass().getClassLoader().getResource("2020101814395601.png").getPath();

        //标题
        HashMap title = new HashMap() {{
            put("title",Texts.of("4.系统日志访问用户top10统计").fontSize(12).bold().create());
        }};

        //图片
        HashMap value = new HashMap() {{
            put("value", Pictures.ofBase64(base64, PictureType.PNG).center().create());
        }};

        //表格
        HashMap table = new HashMap() {{
            // 第0行居中且背景为蓝色的表格
            RowRenderData row0 = Rows.of("序号", "用户名", "次数").center().create();
            put("table", Tables.create(row0));
            String id;

            //结果集
            List renderDataList = new ArrayList<>();
            renderDataList.add(row0);
            for (int i = 0; i < 6; i++) {
                id = String.valueOf(i+1);
                RowRenderData rowi = Rows.create(id, "酷酷酷", "100");
                renderDataList.add(rowi);
            }
            //list转数组
            RowRenderData[] rowRenderDatas = renderDataList.toArray(new RowRenderData[renderDataList.size()]);

            put("table", Tables.create(rowRenderDatas));
        }};

        List> listMap = new ArrayList<>();
//        listMap.add(theme);
        listMap.add(title);
        listMap.add(value);
        listMap.add(table);
        Map map = new HashMap<>();
        map.put("sections",listMap);
        XWPFTemplate template = XWPFTemplate.compile(filePath).render(map);

        //=================生成文件保存在本地文件目录下=================
        //生成临时文件存放地址
        String temDir=fileServcie.docxPath();
        //文件名  带后缀
        String fileName = "login.docx";
        FileOutputStream fos = new FileOutputStream(temDir+ CommonConstant.SEPARATOR +fileName);
        template.write(fos);
        PoitlIOUtils.closeQuietlyMulti(template, fos);
    }
}

你可能感兴趣的:(word,spring,maven,后端,mvc)