SpringBoot生成base64格式的Excel文件进行下载
Xplorist Lv6

SpringBoot生成base64格式的Excel文件进行下载

SpringBoot

  • Excel数据模型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@ApiModel("公交路线站点导出Excel-model")
//@ContentRowHeight(20)
//@HeadRowHeight(30)
//@ColumnWidth(25)
@Data
public class ExcelBusLineStation {
@ExcelProperty("序号")
private String orderNum;
@ColumnWidth(20)
@ExcelProperty("公交路线")
private String busLine;
@ExcelProperty("车辆数")
private String busNum;
@ExcelProperty("分公司")
private String branchOffice;
@ColumnWidth(40)
@ExcelProperty("总站")
private String masterStation;
@ColumnWidth(255)
@ExcelProperty("经停站")
private String intermediateStop;
}
  • SpringBoot中使用EasyExcel生成Excel文件,并转换成byte数组,返回前端时,Spring框架自动将byte数组转换成base64格式的文本
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
@Override
public CommonResult<?> exportBusLineStation(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<ExcelBusLineStation> excelDataList = new ArrayList<>();

// TbBusLineMapper【07】查询所有有效数据
List<TbBusLine> tbBusLines = tbBusLineMapper.listAllValid();
for (int i = 0; i < tbBusLines.size(); i++) {
TbBusLine tbBusLine = tbBusLines.get(i);
String id = tbBusLine.getId();

// 查询车辆数
List<String> busNumList = tbDevicesInfoMapper.listBusNumByLineId(id);

// 查询总站和经停站
TbBusLineStationRel relParam = new TbBusLineStationRel();
relParam.setTbBusLineId(id);
relParam.setUpDownType("up");
// TbBusLineStationRelMapper【02】查询list-by-公交路线id和上下线类型-顺序-by-序号
List<TbBusLineStationRel> lineStations = tbBusLineStationRelMapper.listByBusLineIdUpDownType(relParam);

String masterStation = "";
StringBuilder intermediateStop = new StringBuilder();
for (int j = 0; j < lineStations.size(); j++) {
TbBusLineStationRel rel = lineStations.get(j);
String tbBusStationId = rel.getTbBusStationId();
TbBusStation tbBusStation = tbBusStationMapper.selectByPrimaryKey(tbBusStationId);
String stationName = tbBusStation.getName();
if (j == 0) {
masterStation += stationName + "->";
intermediateStop.append(stationName).append("->");
} else if (j == lineStations.size() - 1) {
masterStation += stationName;
intermediateStop.append(stationName);
} else {
intermediateStop.append(stationName).append("->");
}
}

ExcelBusLineStation item = new ExcelBusLineStation();
item.setOrderNum("" + (i + 1));
item.setBusLine(tbBusLine.getName());
item.setBusNum("" + busNumList.size());
item.setBranchOffice(" ");
item.setMasterStation(masterStation);
item.setIntermediateStop(intermediateStop.toString());
excelDataList.add(item);
}

ByteArrayOutputStream os = new ByteArrayOutputStream();
EasyExcel.write(os, ExcelBusLineStation.class).sheet("1").doWrite(excelDataList);
byte[] bytes = os.toByteArray();
String dateStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String fileOriginName = "公交路线站点汇总" + "-" + dateStr + ".xlsx";
response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
response.setCharacterEncoding("utf-8");
response.addHeader("Content-Disposition", "attachment; filename="
+ new String((URLEncoder.encode(fileOriginName, StandardCharsets.UTF_8.toString())).getBytes(StandardCharsets.UTF_8),
"ISO8859-1"));
return CommonResult.success(bytes);
}

Vue2下载base64格式的Excel文件

HTML

  • index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<div id="app">
<button v-on:click="exportBusLineStation()">导出公交站点Excel</button>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
<script type="text/javascript" src="./js/index.js"></script>
</html>

JavaScript

  • ./js/index.js
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
let app = new Vue({
el: '#app',
data: {

},
created: function () {

},
methods: {
dataURLtoBlob: function (dataurl) {
try {
let arr = dataurl.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);

while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
} catch {
let arr = dataurl.split(',');
let bstr = atob(arr[0]);
let n = bstr.length;
let u8arr = new Uint8Array(n);

while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr]);
}
},
exportBusLineStation: function () {
axios({
method: 'post',
url: '/api/device/baseData/exportBusLineStation',
data: {}
}).then(response => {
let contentDisposition = response.headers['content-disposition'];
let fileName = contentDisposition.substring(contentDisposition.indexOf('=') + 1);
let data = this.dataURLtoBlob(response.data.data);
let url = window.URL.createObjectURL(new Blob([data]));
let link = document.createElement('a');
link.href = url; // <a>下载文件
//this.imgSrc = url; // <img>显示图片
link.setAttribute('download', decodeURIComponent(fileName));
document.body.appendChild(link);
link.click();
}).catch(error => {
alert("文件下载失败");
console.log(error);
});
},
},
});
 评论