引入 easyExcel
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.7</version>
</dependency>
easyexcel 的实体
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.HeadStyle;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import org.apache.poi.ss.usermodel.FillPatternType;
@Data
@ApiModel(value = "允许值列表模板")
@HeadStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 24)
public class AllowValueTemplate {
@ColumnWidth(value = 60)
@ExcelProperty("编码(必填)(不超过30个字符)")
private String allowValueCode;
@ColumnWidth(value = 60)
@ExcelProperty("名称(必填)(不超过20个字符)")
private String allowValueName;
}
Controller 的关键代码
@PostMapping("/uploadAllowValueTemplate")
@ApiOperation(value = "XXX--模板下载",notes = "XXX模板下载", produces = "application/octet-stream")
public void uploadAllowValue(HttpServletResponse response,
@RequestBody String grade) throws IOException {
// 使用swagger 会导致各种问题,请直接用浏览器或者用postman
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("模板下载", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
List<Object> list = Lists.newArrayList();
AllowValueTemplate allowValueTemplate1 = new AllowValueTemplate();
allowValueTemplate1.setAllowValueCode("例如:AAA");
allowValueTemplate1.setAllowValueName("例如:AAA系统");
list.add(allowValueTemplate1);
AllowValueTemplate allowValueTemplate2 = new AllowValueTemplate();
allowValueTemplate2.setAllowValueCode("例如:BBBB");
allowValueTemplate2.setAllowValueName("例如:BBBB系统");
list.add(allowValueTemplate2);
EasyExcel.write(response.getOutputStream(), AllowValueTemplate.class)
.sheet("模板").doWrite(list);
}
vue代码
<el-button class="el-button--long" icon="el-icon-download" @click="downloadFile">模版下载</el-button>
downloadFile(){
let fileName = "xxxx模板下载";
downloadAllowValueTemplate().then(res => {
console.log(res);
downloadExcel(fileName, res);
});
},
/**
* @Description:下载Excel文件
* @author xxxx
* @date 2024/3/27
*/
export function downloadExcel(fileName,val) {
let link = document.createElement('a')
let blob = new Blob([val], {type: 'application/vnd.ms-excel;charset=utf-8'});
link.style.display = 'none';
link.download = fileName+dateFormat(new Date().getTime())+'.xlsx';
link.href = URL.createObjectURL(blob);
// link.setAttribute('download', fileName+'.xlsx');
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href); // 释放URL 对象
document.body.removeChild(link);
}