微信小程序导出excel

前端代码

createReport(){
				this.checkedList=[];
				for(let i=0;i<this.searchList.length;i++){
					for(var j = 0; j < this.searchList[i].keyword.length; j++) {
						var item = this.searchList[i].keyword[j];
						this.$set(item,'deptName',this.searchList[i].name); //向数组中加入元素
						this.$set(item,'type',this.searchList[i].type);
						if(item.checked){
							this.checkedList.push(item);
						}
					}
				}
				var that=this;
				uni.showLoading({
					title: "报表正在生成...",
					mask: true
				});
				uni.request({
					url: baseconfig.server+'/affairs/createReport',
					method: 'POST',
					dataType: 'json',
					contentType : "application/json",
					header:{
						'content-type':'application/x-www-form-urlencoded'
					},
					data: {
						checkedList:JSON.stringify(this.checkedList)
					},
					responseType: 'arraybuffer', //此处是请求文件流,必须带入的属性
					success(res) {
						if (res.statusCode === 200) {
							console.log("200");
							const fs = wx.getFileSystemManager(); //获取全局唯一的文件管理器
							fs.writeFile({
								filePath: wx.env.USER_DATA_PATH + "/统计报表.xls", // wx.env.USER_DATA_PATH 指定临时文件存入的路径,后面字符串自定义
								data: res.data,
								encoding: "binary", //二进制流文件必须是 binary
								success(res) {
									console.log("success(res)",res);
									wx.openDocument({ // 打开文档
										filePath: wx.env.USER_DATA_PATH + "/统计报表.xls", //拿上面存入的文件路径
										showMenu: true, // 显示右上角菜单
										success: function(res) {
											console.log("successfun",res);
											setTimeout(() => {
												uni.hideLoading();//隐藏加载样式
											}, 500);
										},fail:function(res){
											console.log("failfun",res);
										}
									})
								},
								fail(res){
									console.log("fail",res);
								}
							})
						}else{
							console.log("不是200");
						}
						console.log("success",res);
					},
					fail(err) {
						console.log('导出失败:', err);
					}
				})
			},  
后端代码
@RequestMapping(value = "/createReport")
    @ResponseBody
    public Object createReport(HttpServletRequest req, HttpServletResponse resp,@RequestParam(name="checkedList",required = false) String checkedList)throws IOException {
        JSONArray jsonArray= JSONArray.fromObject(checkedList);
        List<Map> list = JSONObject.parseArray(jsonArray.toString(), Map.class);
        String type="";
        for (Map map : list) {
            type=map.get("type").toString();
            String[] strArray = map.get("headlines").toString().split(":");
            if(strArray.length>1){
                String attributeName=strArray[0];
                String attributeValue=strArray[1];
                map.put("attributeName",attributeName);
                map.put("attributeValue",attributeValue);
            }else{
                String attributeName=strArray[0];
                //String attributeValue=strArray[1];
                map.put("attributeName",attributeName);
                map.put("attributeValue",null);
            }
        }
        List<ReportExportModel> modelist=affairsService.buildReportModelByList(list);
        ExportParams exportParams=new ExportParams(type+"统计表","统计数据");
        exportParams.setStyle(ReportStyle.class);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ReportExportModel.class, modelist);
        String filedisplay = type+"统计表.xls";
        ExportBuilder.buildheaderAndExport(req, resp, filedisplay,workbook);
        return success();
    }
public List<ReportExportModel> buildReportModelByList(List<Map> list){
        List<ReportExportModel> modellist=new ArrayList<>();
        for(Map map:list) {
            ReportExportModel model=new ReportExportModel();
            model.setDeptName(map.get("deptName")!=null?map.get("deptName").toString():null);
            model.setAttributeName(map.get("attributeName")!=null?map.get("attributeName").toString():null);
            model.setAttributeValue(map.get("attributeValue")!=null?map.get("attributeValue").toString():null);
            modellist.add(model);
        }
        return modellist;
    }
public static void buildheaderAndExport(HttpServletRequest req, HttpServletResponse resp,String filename,Workbook workbook) throws IOException {
		buildheader(req,resp,filename);
        OutputStream out = resp.getOutputStream();
        workbook.write(out);
        out.close();
	}
public static void buildheader(HttpServletRequest req, HttpServletResponse resp,String filename) throws UnsupportedEncodingException {
		resp.reset();
		req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/x-download");
        //filename = URLEncoder.encode(filename, "UTF-8");
        //filename=new String(filename.getBytes("utf-8"), "ISO8859-1");
        String headStr = "attachment; filename="" + new String(filename.getBytes("utf-8"), "ISO8859-1") + """;
        resp.addHeader("Content-Disposition", headStr);

	}

 

package com.kdgcsoft.zw.applets.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.handler.inter.IExcelModel;

import java.io.Serializable;

/*
* @Description: 配置excel模板
*/
@SuppressWarnings("serial")
public class ReportExportModel implements Serializable,IExcelModel{
    @Excel(name="单位",needMerge=true,orderNum="0",width=20,mergeVertical=true)  //mergeVertical设置是否纵向合并列
    private String deptName;
	@Excel(name="名称",needMerge=true,orderNum="1",width=20)
	private String attributeName;
	@Excel(name="数值",needMerge=true,orderNum="2",width=20)
	private String attributeValue;
	private Long rownum;
    private String errorMsg;

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }

    public String getAttributeName() {
        return attributeName;
    }

    public void setAttributeName(String attributeName) {
        this.attributeName = attributeName;
    }

    public String getAttributeValue() {
        return attributeValue;
    }

    public void setAttributeValue(String attributeValue) {
        this.attributeValue = attributeValue;
    }

    public Long getRownum() {
        return rownum;
    }

    public void setRownum(Long rownum) {
        this.rownum = rownum;
    }

    @Override
    public String getErrorMsg() {
        return errorMsg;
    }

    @Override
    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
}

  excel表格示例

原文地址:https://www.cnblogs.com/double-s/p/15007454.html