1.导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.6</version>
</dependency>
2.angular代码
export() {
if (!!this.listOfAllData) {
const template = new ExcelTemplate();
const header = ['参数名称', '用途', '参数类型', '单位', '可选值', '描述'];
template.name = '工艺参数表';
template.header = header.map(h => [h]);
template.data = this.listOfAllData.map(data => [
data.name, this.transformUsage(data.usages).join(','), this.transformType(data.type),
data.unit, data.valueCandicatesStr, data.comments]);
console.log('export excel template: %o', template);
this.appService.exportExcel(template);
}
}
ExcelTemplate结构
export class ExcelTemplate {
name: string;
header: string[][] = [];
data: any[][] = [];
}
service代码
exportExcel(template: ExcelTemplate) {
const options = {
responseType: 'blob' as 'json'
};
return this.http.post<Blob>(`/api/excel/export`, template, options)
.pipe(retry(2), catchError(this.handleError.bind(this))).subscribe(rs => {
if (rs) {
const blob = new Blob([rs], {type: 'application/octet-stream'});
saveAs(blob, `${template.name}.xlsx`);
}
});
}
3.springboot代码
@PostMapping(value = "/excel/export")
public void exportExcel(HttpServletResponse response, @RequestBody ExcelTemplate template) throws IOException {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String filename = URLEncoder.encode(template.getName(), "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + filename + ".xlsx");
EasyExcel.write(response.getOutputStream()).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).head(template.getHeader())
.sheet(template.getName()).doWrite(template.getData());
}