vue下载excel以及自适应表格宽度(前后端)

133 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第0天,点击查看活动详情

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

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
</dependency>

easyExcel 开源地址:github.com/alibaba/ea.…

1 excel 文件下载

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

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

方式一:

人为构造 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) =&gt; {
  console.log(err);
});</code></pre><p>方式二:</p><p>使用 js-file-download 包</p><ol><li>get 请求</li></ol><pre><code>axios




.get(后端接口链接, {
responseType: "blob" //返回的数据类型
})
.then((res) => {
fileDownload(res.data, "test111.xlsx");
});

.get(后端接口链接, { responseType: "blob" //返回的数据类型 }) .then((res) => { fileDownload(res.data, "test111.xlsx"); });

  1. post 请求
formData.value.pageNum = 1;
formData.value.pageSize = 200;




axios
.post(后端接口链接, formData.value, {
responseType: "blob" //返回的数据类型
})
.then((res) => {
fileDownload(res.data, "test111.xlsx");
});

axios .post(后端接口链接, formData.value, { responseType: "blob" //返回的数据类型 }) .then((res) => { fileDownload(res.data, "test111.xlsx"); });

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

www.jianshu.com/p/22d...

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

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

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

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

3 自适应 excel 宽度

chowdera.com/2022/02/...

www.codetd.com/en/art...

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&lt;Integer, Map&lt;Integer, Integer&gt;&gt; CACHE = new HashMap&lt;&gt;();

// 适当增加宽度,能避免 数字显示为 * 的问题
public static final int DEFAULT = 2;

protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List&lt;WriteCellData&lt;?&gt;&gt; cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
    boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
    if (needSetWidth) {
        Map&lt;Integer, Integer&gt; maxColumnWidthMap = CACHE.get(writeSheetHolder.getSheetNo());
        if (maxColumnWidthMap == null) {
            maxColumnWidthMap = new HashMap&lt;&gt;();
            CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
        }

        Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
        if (columnWidth &gt;= 0) {
            if (columnWidth &gt; 255) {
                columnWidth = 255;
            }

            Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
            if (maxColumnWidth == null || columnWidth &gt; maxColumnWidth) {
                maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
                writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
            }

        }
    }
}

private Integer dataLength(List&lt;WriteCellData&lt;?&gt;&gt; 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;
            }
        }
    }
}




}

}

3.2 easyExcel 写入文件注册 handler

EasyExcel.write(response.getOutputStream(), DownloadData.class).registerWriteHandler(new ExcelWidthStyleStrategy()).sheet("模板").doWrite(downloadDataList);