• vue下载excel以及自适应表格宽度


    本文使用 SpringBoot + vue + easyExcel 实现导出 Excel 功能,并解决文件中文乱码问题以及 Excel 宽度自适应的问题。需要先导入 pom 包。

    
        com.alibaba
        easyexcel
    
    
    • 1
    • 2
    • 3
    • 4

    easyExcel 开源地址:https://github.com/alibaba/easyexcel

    1 excel 文件下载

    vue中下载excel流文件及设置下载文件名:https://segmentfault.com/a/1190000037500013

    使用 vue-json-excel 控件: https://www.npmjs.com/package/vue-json-excel

    方式一:

    人为构造 a 标签,自动点击。

    PS:注意,文件名称,不能通过上述链接中的 this.filename 获取到。

    axios
        .get(`/api/audit/export`, {
          responseType: "blob" //服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream',默认是'json'
        })
        .then((res) => {
          if (!res) return;
          const blob = new Blob([res.data], { type: "application/vnd.ms-excel" }); // 构造一个blob对象来处理数据,并设置文件类型
    
          if (window.navigator.msSaveOrOpenBlob) {
            //兼容IE10
            navigator.msSaveBlob(blob, this.filename);
          } else {
            const href = URL.createObjectURL(blob); //创建新的URL表示指定的blob对象
            const a = document.createElement("a"); //创建a标签
            a.style.display = "none";
            a.href = href; // 指定下载链接
            a.download = "test.xlsx"; //指定下载文件名
            a.click(); //触发下载
            URL.revokeObjectURL(a.href); //释放URL对象
          }
          // 这里也可以不创建a链接,直接window.open(href)也能下载
        })
        .catch((err) => {
          console.log(err);
        });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    方式二:

    使用 js-file-download 包

    1. get 请求
    axios
    .get(`后端接口链接`, {
      responseType: "blob" //返回的数据类型
    })
    .then((res) => {
      fileDownload(res.data, "test111.xlsx");
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    1. post 请求
    formData.value.pageNum = 1;
    formData.value.pageSize = 200;
    
    axios
    .post(`后端接口链接`, formData.value, {
      responseType: "blob" //返回的数据类型
    })
    .then((res) => {
      fileDownload(res.data, "test111.xlsx");
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2 文件名获取,以及乱码解决

    https://www.jianshu.com/p/22d591ed0c34

    后端设置编码方式为 utf-8

    fileName = URLEncoder.encode("中文excel文件名称", "UTF-8").replaceAll("\\+", "%20");
    
    • 1

    vue 前端:使用 decodeURIComponent 反编译中文文件标题

    let dis = res.headers["content-disposition"];
    let filename = decodeURIComponent(dis.split("attachment;filename*=")[1]);
    
    • 1
    • 2

    3 自适应 excel 宽度

    https://chowdera.com/2022/02/202202160504097268.html

    https://www.codetd.com/en/article/13815011

    3.1 继承 AbstractColumnWidthStyleStrategy 实现一个宽度策略

    这个宽度策略会根据标题的宽度或者内容的宽度设置标题的宽度。

    PS:适当增加宽度,能避免数字显示为 * 的问题;避免时间显示为 # 的问题

    import com.alibaba.excel.enums.CellDataTypeEnum;
    import com.alibaba.excel.metadata.Head;
    import com.alibaba.excel.metadata.data.CellData;
    import com.alibaba.excel.metadata.data.WriteCellData;
    import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
    import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
    import com.qunar.base.meerkat.util.DateUtil;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections4.CollectionUtils;
    import org.apache.poi.ss.usermodel.Cell;
    
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    /**
     * easyExcel 自适应列宽
     *
     */
    @Slf4j
    public class ExcelWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
    
    	private Map> CACHE = new HashMap<>();
        
        // 适当增加宽度,能避免 数字显示为 * 的问题
    	public static final int DEFAULT = 2;
    
    	protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
    		boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
    		if (needSetWidth) {
    			Map maxColumnWidthMap = CACHE.get(writeSheetHolder.getSheetNo());
    			if (maxColumnWidthMap == null) {
    				maxColumnWidthMap = new HashMap<>();
    				CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
    			}
    
    			Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
    			if (columnWidth >= 0) {
    				if (columnWidth > 255) {
    					columnWidth = 255;
    				}
    
    				Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
    				if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
    					maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
    					writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
    				}
    
    			}
    		}
    	}
    
    	private Integer dataLength(List> cellDataList, Cell cell, Boolean isHead) {
    		if (isHead) {
    			return cell.getStringCellValue().getBytes().length + DEFAULT;
    		} else {
    			CellData cellData = cellDataList.get(0);
    			CellDataTypeEnum type = cellData.getType();
    			if (type == null) {
    				return -1;
    			} else {
    				switch (type) {
    					case STRING:
    						return cellData.getStringValue().getBytes().length + DEFAULT;
    					case BOOLEAN:
    						return cellData.getBooleanValue().toString().getBytes().length + DEFAULT;
    					case NUMBER:
    						return cellData.getNumberValue().toString().getBytes().length + DEFAULT;
    					case DATE:
    						return DateUtil.PATTERN_YYYY_MM_DD_HH_MM_SS.getBytes().length + DEFAULT;
    					default:
    						return -1;
    				}
    			}
    		}
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77

    3.2 easyExcel 写入文件注册 handler

    EasyExcel.write(response.getOutputStream(), DownloadData.class).registerWriteHandler(new ExcelWidthStyleStrategy()).sheet("模板").doWrite(downloadDataList);
    
    • 1
  • 相关阅读:
    唯品会的两个常用API分享(商品详情和关键字搜索)
    社区街道治安智慧监管方案,AI算法赋能城市基层精细化治理
    黑马头条(day01)
    第 300 场周赛 - 力扣(LeetCode)
    Algorithm Review 4
    DC电源模块的数字电源优势
    ubuntu安装nps客户端
    【手把手带你学Java EE】HTTP协议
    jvm双亲委派机制详解
    Julia绘图初步:Plots
  • 原文地址:https://blog.csdn.net/Prepared/article/details/126292204