springBoot下使用easePoi 导出word

前端使用框架使用的是VUE
前端代码

import request from '@/router/axios';
export function exportData(query) {
    return request({
        url: '/manage/agency/projectsApprovalLedgers/export',
        method: 'get',
        params: query,
        responseType: 'blob'
    });
}

doExport(){
	exportData(this.listQuery).then(resp=>{
	    let blob = new Blob([resp]);
	        let url = URL.createObjectURL(blob);
	        let a = document.createElement('a');
	        a.style.display = 'none';
	        a.setAttribute('href', url);
	        a.setAttribute('download', '代办服务台账.docx');
	        document.body.appendChild(a);
	        a.click();
	        URL.revokeObjectURL(blob);
	        document.body.removeChild(a);
	        this.btnLoadingExport = false;
	})
}

后端代码
pom.xml文件

<!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-spring-boot-starter -->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-spring-boot-starter</artifactId>
            <version>4.4.0</version>
        </dependency>
// controller忽略
// ...
//serviceImpl层
@Override
    public void export(ProjectsApprovalLedgersVo projectsApprovalLedgersVo,HttpServletRequest request, HttpServletResponse response) throws Exception {
        projectsApprovalLedgersVo.setPage(1l).setSize(5000l);
        List<ProjectsApprovalLedgersVo> dataList = this.myPageByBean(projectsApprovalLedgersVo).getRecords();
        List<ProjectsApprovalLedgersVo> dataVos = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(dataList)) {
            dataVos = this.setVoProperties(dataList);
        }
        // 这里可以通过id查找数据库中保存的信息,这里就不查数据库了,大概数据数据测试就行了
        // 读取word文档模板
        //获取resources目录文件对象
        /**
       	 * 只能本地读取到模版文件,打包后jar中没有具体路径会报空指针异常
         * File rootFile = new File((ResourceUtils.getURL("classpath:").getPath()));
         * File templateFile = new File(rootFile.getAbsolutePath() + "/templates/agencyAccountTemplate.docx");
         * log.info("templateFile:{}", templateFile);
         **/
        ClassPathResource resource = new ClassPathResource("templates/agencyAccountTemplate.docx");
        InputStream inputStream = resource.getInputStream();
        // 需要将bean转换为map集合
        Map<String, Object> maps = new HashMap<>();
        if (CollectionUtil.isEmpty(dataList)) {
            maps.put("year", DateUtil.year(new Date()));
        }else {
            maps.put("year",dataList.get(0).getYear());
        }
        // 写入图片
        // ImageEntity imageEntity = new ImageEntity();
        // // 这里可以是磁盘地址,也可以是对应的http地址,例如在springboot中static下的图片可以直接通过http的url访问。
        // imageEntity.setUrl("http://localhost:8080/img/1.jpg");
        // // 这里的宽高必须要设置
        // imageEntity.setWidth(500);
        // imageEntity.setHeight(300);
        // maps.put("photo",imageEntity);
        // ImageEntity imageEntity1 = new ImageEntity();
        // imageEntity1.setUrl("D:\\private\\javastudaykeshanchu\\javaweb\\wordexport\\src\\main\\resources\\static\\img\\2.jpg");
        // imageEntity1.setWidth(500);
        // imageEntity1.setHeight(300);
        // maps.put("photo1",imageEntity1);

        // 这里以集合List的形式,在word模板中使用模板指令fe:遍历数据,创建row

        List<Dictionary> dictList = adminFeign.getDictionaryByIndexId("agency_project_business").getData();
        if (CollectionUtil.isNotEmpty(dictList)) {
            Map<String, String> dictMap = dictList.stream().collect(Collectors.toMap(Dictionary::getCode, Dictionary::getCodeText));
            dataVos.forEach(item -> {
                String projectTypeName = dictMap.get(item.getProjectType());
                item.setProjectTypeName(StrUtil.isNotBlank(projectTypeName) ? projectTypeName : item.getProjectType());
                String levelName;
                switch (item.getProjectLevel()) {
                    case "city":
                        levelName = "市级";
                        break;
                    case "county":
                        levelName = "区级";
                        break;
                    default:
                        levelName = "非重点";
                }
                item.setProjectLevelName(levelName);
            });
        }
        maps.put("dataList", dataVos);
        ExportWordUtils.exportWord(inputStream,"/deya/vhost/temp/","代办服务台账.docx", maps, request,response);
    }
package com.kang.agency.utils;

import cn.afterturn.easypoi.word.WordExportUtil;
import cn.afterturn.easypoi.word.entity.MyXWPFDocument;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;
 
public class ExportWordUtils {
 
    /**
     * 导出word
     * <p>第一步生成替换后的word文件,只支持docx</p>
     * <p>第二步下载生成的文件</p>
     * <p>第三步删除生成的临时文件</p>
     * 模版变量中变量格式:{{foo}}
     *
     * @param is       word模板文件流
     * @param temDir   生成临时文件存放地址
     * @param fileName 文件名
     * @param params   替换的参数
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     */
    public static void exportWord(InputStream is, String temDir, String fileName, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        Assert.notNull(is, "模板不能为空");
        Assert.notNull(temDir, "临时文件路径不能为空 ");
        Assert.notNull(fileName, "导出文件名不能为空 ");
        Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");
        if (!temDir.endsWith("/")) {
            temDir = temDir + File.separator;
        }
        File dir = new File(temDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            String userAgent = request.getHeader("user-agent").toLowerCase();
            if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
            }
 
            MyXWPFDocument doc = new MyXWPFDocument(is);
            WordExportUtil.exportWord07(doc, params);
 
            String tmpPath = temDir + fileName;
            FileOutputStream fos = new FileOutputStream(tmpPath);
            doc.write(fos);
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            // 设置文件名
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            OutputStream out = response.getOutputStream();
            doc.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            delFileWord(temDir, fileName);//这一步看具体需求,要不要删
            try {
                is.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
 
    /**
     * 删除零时生成的文件
     */
    public static void delFileWord(String filePath, String fileName) {
        File file = new File(filePath + fileName);
        File file1 = new File(filePath);
        file.delete();
        file1.delete();
    }
}

word模版文件
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在 Spring Boot 中实现 Word 动态导出,可以使用 Apache POI 这个 Java 库来生成 Word 文档。下面是一个简单的实现过程: 1. 添加 Apache POI 依赖 在 pom.xml 文件中添加以下依赖: ```xml <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> ``` 2. 创建 Word 模板 使用 Microsoft Word 创建一个模板,将需要动态填充的部分用 ${} 包裹起来,例如: ``` ${title} ${content} ``` 3. 编写生成 Word 文档的代码 编写一个方法,读取 Word 模板文件,使用 Apache POI 替换模板中的占位符,生成新的 Word 文档。以下是一个简单的示例代码: ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import java.io.*; import java.util.HashMap; import java.util.Map; public class WordGenerator { public void generateWord(Map<String, String> data) throws Exception { // 读取 Word 模板文件 InputStream is = new FileInputStream("template.docx"); XWPFDocument docx = new XWPFDocument(is); // 替换模板中的占位符 for (XWPFParagraph p : docx.getParagraphs()) { for (XWPFRun r : p.getRuns()) { String text = r.getText(0); if (text != null) { for (Map.Entry<String, String> entry : data.entrySet()) { if (text.contains(entry.getKey())) { text = text.replace(entry.getKey(), entry.getValue()); r.setText(text, 0); } } } } } // 保存生成的 Word 文档 OutputStream os = new FileOutputStream("output.docx"); docx.write(os); os.close(); docx.close(); is.close(); } } ``` 4. 调用生成 Word 文档的方法 在 Spring Boot 中,可以将生成 Word 文档的方法封装在一个 RESTful 接口中,例如: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController public class WordController { @GetMapping("/word") public String generateWord() throws Exception { Map<String, String> data = new HashMap<>(); data.put("${title}", "这是标题"); data.put("${content}", "这是内容"); WordGenerator generator = new WordGenerator(); generator.generateWord(data); return "生成成功"; } } ``` 访问 /word 接口即可生成 Word 文档。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值