WORD模板替换,将文件给前端下载

WORD模板替换,将文件给前端下载_第1张图片

1.word模板设计填充字段加{{填充字段名}}

2.后端依赖

1.7.3
4.1.2

    com.deepoove
    poi-tl
    ${poi-tl.version}


    org.apache.poi
    poi
    ${poi.version}

3.后端代码

3.1工具类

package com.ruoyi.common.utils.poi;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.policy.HackLoopTableRenderPolicy;
import com.ruoyi.common.utils.uuid.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;

public class WordUtil {

    public static void test(Object data, String filePath, HttpServletResponse response) {
        HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
        Configure config = Configure.newBuilder().bind("list", policy).build();
        XWPFTemplate template = XWPFTemplate.compile(filePath, config).render(data);//调用模板,填充数据
        /*src\main\resources\wordTemplate\test.docx*/
        String uuid = UUID.randomUUID().toString();
        try {

            FileOutputStream out = new FileOutputStream("C:\\Users\\ZDHS\\Desktop\\"+uuid+".docx");//要导出的文件名
            template.write(out);
            out.flush();
            out.close();
            template.close();
            /*==*/
            String fileName = "Operator.docx"; // 文件的默认保存名
            // 读到流中
            InputStream inStream = new FileInputStream("C:\\Users\\ZDHS\\Desktop\\"+uuid+".docx");// 文件的存放路径
            // 设置输出的格式
            response.reset();
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            try {
                while ((len = inStream.read(b)) > 0)
                    response.getOutputStream().write(b, 0, len);
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            /*==*/

        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            Files.delete(Paths.get("C:\\Users\\ZDHS\\Desktop\\" + uuid + ".docx"));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

3.2接口类

//@PreAuthorize("@ss.hasPermi('system:selection:export')")
//@Log(title = "技术参数", businessType = BusinessType.EXPORT)
@PostMapping("/wordTemplate")
public void wordTemplate(HttpServletResponse response, HttpServletRequest request, HistoryVo history) {
    /*todo:处理数据*/
    WordUtil.test(history,"todo:文件路径",response);
}

4.前端事件方法

handleDownload(row) {

      this.queryParams = row

      console.log(row)

      this.download('system/selection/wordTemplate', {

        ...this.queryParams

      }, `selection_${new Date().getTime()}.docx`)

    },

你可能感兴趣的:(前端,java)