在项目中需要一个导出excel的小功能,轻轻松松就写完了,结果一测发现,文件打不开,哎呦,这个急人哦,纠结了半天,终于解决了,亲测有效,看来做事,凡事都要认真,有什么不足的地方,希望大家多多指正。
原本代码:
/*导出事件*/
function handleDownload() {
exportUnMeasurePoint({}).then((res: any) => {
console.log('下载啦啦啦',res)
//1.我们需要通过blob对象来处理,需要模拟一个<a>标签来提供下载链接
const elink = document.createElement('a');
elink.style.display = 'none';
//2.blob是二进制大对象,接受后台返回的数据流,导出数据
const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet' });
//3.创建一个url 对象,并将blob实例作为参数传入,这样href的值就是以blob开头的一个文件流下载链
接,类似于href="blob:http://127.0.0.1xxxxx"
const blobUrl = URL.createObjectURL(blob);
elink.href = blobUrl;
elink.download = "数据.xls";//下载后的文件名
document.body.appendChild(elink);
elink.click();
document.body.removeChild(elink);
})
}
接口url:
export const exportUnMeasurePoint = (params: any) =>
defHttp.get<InspectionGetResultModel>({url: Api.exportUnMeasurePoint, params});
java代码:
/**
* 导出接口
*/
@GetMapping("/exportUnMeasurePoint.do")
public void exportUnMeasurePoint(HttpServletResponse response){
List<FsuDeviceVo> data = list;//要导出的list
XSSFWorkbook workbook = new XSSFWorkbook();
// 获取第一个表单Sheet
XSSFSheet sheetAt = workbook.createSheet();
//创建第一行row
XSSFRow header=sheetAt.createRow(0);
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.LIGHT_ORANGE.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//创建单元格并插入表头
XSSFCell cell=null;
String[] infos={"名称1","名称2","FSUID","设备ID","设备名称","Tag"};
for(int i=0;i<infos.length;i++){
cell=header.createCell(i);
cell.setCellValue(infos[i]);
cell.setCellStyle(cellStyle);
}
for (int i = 1; i <= data.size(); i++) {
FsuDeviceVo fsuDeviceVo = data.get(i - 1);
XSSFRow dataRow=sheetAt.createRow(i);
XSSFCell cell0=dataRow.createCell(0);
cell0.setCellValue(fsuDeviceVo.getRoomId());
XSSFCell cell1=dataRow.createCell(1);
cell1.setCellValue(fsuDeviceVo.getRoomName());
XSSFCell cell2=dataRow.createCell(2);
cell2.setCellValue(fsuDeviceVo.getFsuId());
XSSFCell cell3=dataRow.createCell(3);
cell3.setCellValue(fsuDeviceVo.getDeviceId());
XSSFCell cell4=dataRow.createCell(4);
cell4.setCellValue(fsuDeviceVo.getDeviceName());
XSSFCell cell5=dataRow.createCell(5);
cell5.setCellValue(fsuDeviceVo.getTag());
}
//文件输出流
try {
String fileName = URLEncoder.encode("表格数据.xlsx","utf-8");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="+fileName);
OutputStream outputStream = new
BufferedOutputStream(response.getOutputStream());
//写入
workbook.write(outputStream);
//关闭输出流
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
这看起来也没什么问题啊,文件也能下载成功,可惜就是打不开,也尝试了,wps恢复,纠结。。。
终于想到原因了
export const exportUnMeasurePoint = (params: any) =>
defHttp.get<InspectionGetResultModel>({url: Api.exportUnMeasurePoint, responseType: 'blob'});
下载成功,excel也能打开了。