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

1.官方文档 Poi-tl Documentation

word 模板 准备 .docx 文件

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

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

 

 官网中文本设置样式

 

传入图片

 controller层

代码:

引入依赖,注意版本冲突

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.1.2</version>
</dependency>

<dependency>
    <groupId>com.deepoove</groupId>
    <artifactId>poi-tl</artifactId>
    <version>1.10.0</version>
</dependency>

 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<String, Object> theme = new HashMap<String, Object>() {{
            put("theme",Texts.of("日志报表").fontSize(22).bold().create());
        }};

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

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

            //结果集
            List<RowRenderData> 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<Map<String,Object>> listMap = new ArrayList<>();
        listMap.add(theme);
        listMap.add(title);
        listMap.add(value);
        listMap.add(table);
        Map<String,Object> 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<String, Object> title = new HashMap<String, Object>() {{
            put("title",Texts.of("2.系统日志操作结果统计").fontSize(12).bold().create());
        }};

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

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

            //结果集
            List<RowRenderData> 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<Map<String,Object>> listMap = new ArrayList<>();
//        listMap.add(theme);
        listMap.add(title);
        listMap.add(value);
        listMap.add(table);
        Map<String,Object> 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<String, Object> title = new HashMap<String, Object>() {{
            put("title",Texts.of("3.监控日志操作结果统计").fontSize(12).bold().create());
        }};

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

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

            //结果集
            List<RowRenderData> 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<Map<String,Object>> listMap = new ArrayList<>();
//        listMap.add(theme);
        listMap.add(title);
        listMap.add(value);
        listMap.add(table);
        Map<String,Object> 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<String, Object> title = new HashMap<String, Object>() {{
            put("title",Texts.of("4.系统日志访问用户top10统计").fontSize(12).bold().create());
        }};

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

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

            //结果集
            List<RowRenderData> 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<Map<String,Object>> listMap = new ArrayList<>();
//        listMap.add(theme);
        listMap.add(title);
        listMap.add(value);
        listMap.add(table);
        Map<String,Object> 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);
    }
}

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值