Descarga de datos complementarios según la plantilla de Word

Para usar EasyWord, el POM necesita agregar dependencias primero

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>        
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.17</version>
        </dependency>
        <!--easyword导出word 依赖		-->
        <dependency>
            <groupId>com.sushengren</groupId>
            <artifactId>easyword</artifactId>
            <version>1.1.3</version>
        </dependency>

jsp código frontal

    //导出word
    $("#downLoadWord").click(function () {
       var time = '${createTime}';
       var url = '${ctx}/systemSituation/exportWord.html?createTime='+time;
        var form = document.createElement('form'); //创建form标签
        form.setAttribute("style","display:none");
        form.setAttribute("method","post");//设置请求方式
        var exportData = ''  //设置发送后台数据
        form.setAttribute("action",url); //action属性设置请求路径
        document.body.appendChild(form); //页面添加form标签

        var input1 = document.createElement("input") //创建input标签
        input1.setAttribute("type","hidden") //设置隐藏域

        form.appendChild(input1);
        form.submit();//表单提交即可下载!
        document.body.removeChild(form); //页面删除form标签
    });

código de fondo

//controller 层
    @RequestMapping("exportWord")
    public void exportWord(HttpServletResponse response, Model model) throws IOException {
        Pagination pagination = new Pagination(this.getRequest());
        Map<String, Object> map = pagination.getConditions();
        PlatformFormTemplate data = systemSituationManager.assembleData(MapUtils.getString(map,"createTime"));
        ServletOutputStream out = null;
        try {
            //设置浏览器导出word格式文件
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            //设置字符集
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码  注意这里Chrome仍然会乱码
            String fileName = MapUtils.getString(map, "createTime") + "阳光平台运行情况";
            if (this.getRequest().getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
                fileName = new String(fileName.getBytes("GB2312"), "ISO-8859-1");
            } else {
                // 对文件名进行编码处理中文问题
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
                fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
            }
            //设置导出word文件格式
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName+ ".docx");

            // 模板路径
            File file = new File("D:\\导出模板.docx");
            //以流的形式 获取resources下目中录模板文件--这边有问题 读取不了
//            InputStream file = new ClassPathResource("templates/export.docx").getInputStream();
            // 导出本地地址
//            FileOutputStream out = new FileOutputStream("D:\\" + MapUtils.getString(map, "createTime") + "阳光平台运行情况.docx");
//            EasyWord.of(file).doWrite(data).toOutputStream(out);

            out = response.getOutputStream();
            EasyWord.of(file).doWrite(data).toOutputStream(out);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map1 = new HashMap();
            map1.put("status", "failure");
            map1.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map1));
        }finally {
            out.close();
        }
    }

La plantilla de Word establece el marcador de posición {}.

 clase de entidad correspondiente

package com.hsnn.medstgmini.suppur.export;

import com.sushengren.easyword.EasyWord;
import com.sushengren.easyword.annotation.WordProperty;
import lombok.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * /sup/systemSituation/toReportDetail.html  页面导出word 模板
 *
 * @author :chengang
 * @date :Created in 2022/8/15 17:50
 */
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PlatformFormTemplate {
    /**
     *  一、基础库整体情况
     */
    @WordProperty("日期")
    private String date;
    @WordProperty("已注册企业")
    private Integer companyNum;
    @WordProperty("生产企业")
    private Integer companyScNum;
    @WordProperty("配送企业")
    private Integer companypsnum;

}



Ensamblar servicio de datos


    @Override
    public PlatformFormTemplate assembleData(String createTime) {

        return  PlatformFormTemplate.builder()
                .date("aaaa")
                .companyNum("cccccc")
                .companyScNum("bbbbbb")
                .companypsnum("dddddd")
                .build();

    }

---Si es una página vue, la interfaz es la siguiente

<el-button type="primary" plain @click="downloadTemplate"
>下载word</el-button>


//方法部分
    downloadTemplate() {
      dowrequest.post('/tps-local-bd/web/mcstrans/apiDeliveryProtocol/exportWord'
        , null
        , {'responseType': 'blob'}
      ).then(res => {
          debugger
          const { data } = res
          let fileName = `配送协议模板`
          exportFile(data, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', fileName)

        })
        .catch(err => {
          console.log(err);
        })

    },


export function exportFile(data,type, fileName) {
  let blob = new Blob([data], {
    //type类型后端返回来的数据中会有,根据自己实际进行修改
    // 表格下载为 application/xlsx,压缩包为 application/zip等,
    type: type
  });
  let filename = fileName;
  if (typeof window.navigator.msSaveBlob !== "undefined") {
    window.navigator.msSaveBlob(blob, filename);
  } else {
    var blobURL = window.URL.createObjectURL(blob);
    // 创建隐藏<a>标签进行下载
    var tempLink = document.createElement("a");
    tempLink.style.display = "none";
    tempLink.href = blobURL;
    tempLink.setAttribute("download", filename);
    if (typeof tempLink.download === "undefined") {
      tempLink.setAttribute("target", "_blank");
    }
    document.body.appendChild(tempLink);
    tempLink.click();
    document.body.removeChild(tempLink);//移除dom元素
    window.URL.revokeObjectURL(blobURL);//释放bolb内存
  }
}

Referencia: herramienta de documento de Word de exportación JAVA EasyWord

Supongo que te gusta

Origin blog.csdn.net/qq_37570710/article/details/126381618
Recomendado
Clasificación