java进行后台数据写入word模板再进行压缩包下载

createh51个月前 (02-01)技术教程19

经常会遇到这样需求,写一个导出功能,进行word模板格式进行导出,数据库相应数据回填到word模板中,再对这个模板进行导出功能。如果一次性需要导出多个模板情况下,就要对多个进行压缩成一个压缩包再一次性导出。

废话不多说直接上代码:

需要导入相应jar包:

controller层:

@GetMapping(value = "/export")
public void export(HttpServletResponse response) {
    try {
        taskServic.exportWordZip(response);
    } catch (Exception e) {
        logger.error("导出失败", e);
    }
}

service层:

/**
 * 获取当前系统的临时目录
 */
public final static String SRC_PATH = System.getProperty("java.io.tmpdir");
/**
 * 导出(zip)
 * @param response
 */
public void exportWordZip( HttpServletResponse response) {
    List<File> files = new ArrayList<>();
   //数据库查出来数据--模拟写个测试数据
    DemoVO vo = new DemoVO();
    vo.setName("测试模板数据"+System.currentTimeMillis());
    String zipFileName = "测试模板数据";
    // 动态获取模板名称
    String templateName = "demo.docx";
    //模板
    String fileName = System.currentTimeMillis()+"";
    //要写入模板里数据
    String tempFileTemplate = generate(vo, templateName, fileName);
    if (tempFileTemplate != null) {
        files.add(new File(tempFileTemplate));
    }
    //压缩包下载
    if (files != null) {
        zipDownload(response, zipFileName + "_" + System.currentTimeMillis() + ".zip", files);
    }
}
/**
 * 生成-模板-数据写入.docx文件模板
 *
 * @return
 */
public String generate(Object object, String templateName, String fileName) {
    // 获取当前系统的临时目录
    String filePath = SRC_PATH;
    String addTimeFileName =  fileName;
    //存储的文件路径  File.separator
    String storeFilePath = filePath + addTimeFileName;
    String docxFilePath = storeFilePath + ".docx";
    //后缀
    String suffix = ".docx";
    XWPFTemplate template = null;
    try (OutputStream os = new FileOutputStream(docxFilePath);
         InputStream inputStream = new ClassPathResource("/templates/" + templateName).getInputStream()) {
        DemoVO vo = (DemoVO) object;
        template = XWPFTemplate.compile(inputStream).render(new HashMap<String, Object>() {{
            put("name", vo.getName());
        }});
        template.write(os);
        os.flush();
        return storeFilePath + suffix;
    } catch (Exception e) {
      //  logger.error("生成模板失败", e);
    } finally {
        if (template != null) {
            try {
                template.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}
/**
 * zip打包下载
 *
 * @param response
 * @param zipFileName
 * @param fileList
 */
public void zipDownload(HttpServletResponse response, String zipFileName, List<File> fileList) {
    // zip文件路径
    String zipPath = ZipDownloadUtil.FILE_PATH + zipFileName;
    try {
        //创建zip输出流
        try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath))) {
            //声明文件集合用于存放文件
            byte[] buffer = new byte[1024];
            //将文件放入zip压缩包
            for (int i = 0; i < fileList.size(); i++) {
                File file = fileList.get(i);
                try (FileInputStream fis = new FileInputStream(file)) {
                    out.putNextEntry(new ZipEntry(file.getName()));
                    int len;
                    // 读入需要下载的文件的内容,打包到zip文件
                    while ((len = fis.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }
                    out.closeEntry();
                }
                file.delete();
            }
        }
        //下载zip文件
        ZipDownloadUtil.downFile(response, zipFileName);
    } catch (Exception e) {
      //  logger.error("文件下载出错", e);
    } finally {
        // zip文件也删除
        fileList.add(new File(zipPath));
        ZipDownloadUtil.deleteFile(fileList);
    }
}

看下一个模板内容


看下导出效果:





完美收工。

相关文章

java读写xml文件(java读取xml工具类)

1.读取xml文件文件格式如下: 张无忌 男 光明顶 minmin 3 4...

java实现文件上传到服务器(java实现文件上传的三种方式)

java实现文件上传到服务器,java实现大文件上传,java实现大文件分块上传,java实现大文件分片上传,java实现大文件切片上传,java实现大文件批量上传,java实现大文件加密上传,jav...

Java操作Office:POI之word生成(java生成doc文档)

程序员架构进阶一 背景 最近在项目开发中,有数据导出到word的需求。这就涉及代码生成word文档的操作,且有格式要求。大家用word做过简历的都有了解,做简历时,会使用表格、图片、文字等元素。而且表...

Java高级特性——注解:注解实现Excel导出功能

注解是 Java 的一个高级特性,Spring 更是以注解为基础,发展出一套“注解驱动编程”。这听起来高大上,但毕竟是框架的事,我们也能用好注解吗?的确,我们很少有机会自己写注解,导致我们搞不清楚注解...

2020-12-11:多个线程同时写同一个日志文件,为...

2020-12-11:多个线程同时写同一个日志文件,为什么相互写的内容不会被覆盖?福哥答案2020-12-11:[答案来自此链接:](https://bbs.csdn.net/topics/39851...