阿里工具类前后台导出excel

后台代码

中间层请求

    /**
     * 导出execl
     * @param ordDetailParamDTO
     * @return
     * @throws Exception
     */
    @PostMapping("/orderExportExcel")
    public void orderExportExcel(HttpServletResponse response, @RequestBody OrdDetailParamDTO ordDetailParamDTO) throws Exception {
        List<OrdDetailExportDTO> queryList = orderOpurchaseClient.orderExportExcel(ordDetailParamDTO);
        EasyExcelUtils.writeExcel(response, queryList, "订单明细列表", "订单明细列表");
    }

controller层

   @PostMapping("/exportExcel")
   public List<OrdDetailExportDTO> exportDataToExcel(@RequestBody OrdDetailParamDTO ordDetailParamDTO) {
       log.info("导出订单明细参数", JSON.toJSONString(ordDetailParamDTO));
       List<OrdDetailExportDTO> queryList = new ArrayList<>();
       try {
           queryList = ordBBo.queryExportDetail(ordDetailParamDTO);
       } catch (Exception e) {
           e.printStackTrace();
           log.error("导出竞价产品失败,{}", e);
       }
       return queryList;
   }

工具类:EasyExcelUtils

package cn.hsa.tps.utils;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.StringUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.springframework.beans.BeanUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class EasyExcelUtils {

   protected static FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyyMMddHH:mm:ss");

   /**
    * @param fileName             文件名
    * @param cameraReportStopList 普通vo类
    * @param entityModel          继承BaseRowModel的模型class
    * @param response
    * @param <T>
    */
   public static <T extends BaseRowModel> void baseExportExcel(String fileName, List cameraReportStopList, Class<T> entityModel, HttpServletResponse response) throws InstantiationException, IllegalAccessException {
       List<BaseRowModel> modelList = new ArrayList<>();
       if (StringUtils.isEmpty(cameraReportStopList)) {
           return;
       }
       for (Object cameraReportStopVo : cameraReportStopList) {
           BaseRowModel cameraReportStopModel = entityModel.newInstance();
           BeanUtils.copyProperties(cameraReportStopVo, cameraReportStopModel);
           modelList.add(cameraReportStopModel);
       }
       try {
           writeExcel(response, modelList, fileName + fastDateFormat.format(new Date()), "第一页");
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

   /**
    * 导出 Excel :一个 sheet,带表头
    * @param response  HttpServletResponse
    * @param list      数据 list,每个元素为一个 BaseRowModel
    * @param fileName  导出的文件名
    * @param sheetName 导入文件的 sheet 名
    */
   public static void writeExcel(HttpServletResponse response, List<? extends BaseRowModel> list,
                                 String fileName, String sheetName) throws Exception {
       ExcelWriter writer = new ExcelWriter(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);
       Class clazz = null;
       if (list.size() > 0) {
           clazz = list.get(0).getClass();
       } else {
           clazz = BaseRowModel.class;
       }
       Sheet sheet = new Sheet(1, 0, clazz);
       sheet.setSheetName(sheetName);
       writer.write(list, sheet);
       writer.finish();
   }

   /**
    * 导出文件时为Writer生成OutputStream
    */
   private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
       try {
           fileName = URLEncoder.encode(fileName, "UTF-8");
           response.setContentType("application/vnd.ms-excel");
           response.setCharacterEncoding("utf8");
           response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
           response.setHeader("Pragma", "public");
           response.setHeader("Cache-Control", "no-store");
           response.addHeader("Cache-Control", "max-age=0");
           return response.getOutputStream();
       } catch (IOException e) {
           throw new Exception("导出excel表格失败!", e);
       }
   }
}

前台代码

			//导出
			exportData() {
				let that = this;
				axios({
					method: "post",
					url: process.env.VUE_APP_BASE_API + "/orderExportExcel",
					responseType: "blob",
					headers: {
						Authorization: `${getToken()}`,
						userid: Cookies.get("userid")
					},
					async: false, // fasle表示同步请求,true表示异步请求
					data: that.queryData
				}).then((res) => {
					if (!res) {
						return;
					}
					if (res.code == 666) {
						console.log(res);
					}
					let blob = new Blob([res.data], {
						// type: "application/octet-stream"
						type: "application/vnd.ms-excel"
					});
					let url = window.URL.createObjectURL(blob);
					let link = document.createElement("a");
					link.setAttribute("download", decodeURI("订单明细一键导出表-" + Date.now()) + ".xlsx"); // 文件名
					link.style.display = "none";
					link.href = url;
					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);
					this.gridLoading = false;
				}).catch((error) => {
					that.gridLoading = false;
					that.msgError("导出失败!");
					return;
				});
			}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值