使用场景:需要对前端导入的excel文件中的内容进行验证,如期中有验证失败的信息需要转成excel反馈给前端,用户下载查看信息,并且前端需要获取json返回的状态,给用户提示失败或者成功,所以需要导出json的同时返回excel。
废话不多说,直接上代码
后端代码:
@ApiOperation(value = "接口返回的类型是json格式,里面字段对应base64格式的excel文件", notes = "接口返回的类型是json格式,里面字段对应base64格式的excel文")@RequestMapping(value = "exportDemo")public Map exportDemo() throws Exception {Map map = new HashMap();map.put("success", false);map.put("message", "导入失败");HSSFWorkbook errWorkbook = new HSSFWorkbook(); //创建ExcelHSSFSheet sheet = errWorkbook.createSheet("Sheet1");//创建SheetHSSFRow T_row = sheet.createRow(0);//创建一行表头T_row.createCell(0).setCellValue("必填,学号");//设置表头列名T_row.createCell(1).setCellValue("学生姓名");//设置表头列名T_row.createCell(2).setCellValue("培养单位");//设置表头列名T_row.createCell(3).setCellValue("必填,主导师工号");//设置表头列名T_row.createCell(4).setCellValue("主导师姓名");//设置表头列名T_row.createCell(5).setCellValue("联合导师工号(如有)");//设置表头列名T_row.createCell(6).setCellValue("联合导师姓名(如有)");//设置表头列名T_row.createCell(7).setCellValue("错误信息");//设置表头列名HSSFCellStyle style = errWorkbook.createCellStyle();style.setDataFormat(errWorkbook.createDataFormat().getFormat("@")); // 设置为文本格式for (int i = 0; i < T_row.getPhysicalNumberOfCells(); i++) {sheet.setDefaultColumnStyle(i, style);}for (Cell cell : T_row) {cell.setCellStyle(style);cell.setCellType(CellType.STRING);}ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();// 将EXCEL文件写进流内errWorkbook.write(byteArrayOutputStream);byte[] bytes = byteArrayOutputStream.toByteArray();String base64ExlCode = Base64Utils.encodeToString(bytes);map.put("excel",base64ExlCode);return map;}
前端代码1:
, exportDemo: function () {var self = thisvar url = baseUrl + self.QUERY_URL + '/exportDemo';//定义参数var myform = new FormData();$.ajax({url: url,data: myform,dataType: "json",type: 'post',async: true,//重要,必须设置 falsecontentType: false,//重要,必须设置 falseprocessData: false,beforeSend: function () {self.$Spin.show();},complete: function () {},success: function (res) {alert(res.message)//下载文件var blob = self.dataURLtoBlob(res.excel);var downloadUrl = window.URL.createObjectURL(blob);var anchor = document.createElement("a");anchor.href = downloadUrl;anchor.download = decodeURI("导入错误.xls");anchor.click();}, error: function (data) {self.$Spin.hide();self.$Message.error({content: data.responseText, duration: 5, background: true});}})}
前端代码2:
// 核心 将base64的字符串转为文件流, dataURLtoBlob: function (base64Str) {var bstr = atob(base64Str);var n = bstr.length;var u8arr = new Uint8Array(n);while (n--) {u8arr[n] = bstr.charCodeAt(n);}// 下载的是excel格式的文件return new Blob([u8arr], {type: "application/vnd.ms-excel"});//其他类型:// 'doc' => 'application/msword',// 'bin' => 'application/octet-stream',// 'exe' => 'application/octet-stream',// 'so' => 'application/octet-stream',// 'dll' => 'application/octet-stream',// 'pdf' => 'application/pdf',// 'ai' => 'application/postscript',// 'xls' => 'application/vnd.ms-excel',// 'ppt' => 'application/vnd.ms-powerpoint',// 'dir' => 'application/x-director',// 'js' => 'application/x-javascript',// 'swf' => 'application/x-shockwave-flash',// 'xhtml' => 'application/xhtml+xml',// 'xht' => 'application/xhtml+xml',// 'zip' => 'application/zip',// 'mid' => 'audio/midi',// 'midi' => 'audio/midi',// 'mp3' => 'audio/mpeg',// 'rm' => 'audio/x-pn-realaudio',// 'rpm' => 'audio/x-pn-realaudio-plugin',// 'wav' => 'audio/x-wav',// 'bmp' => 'image/bmp',// 'gif' => 'image/gif',// 'jpeg' => 'image/jpeg',// 'jpg' => 'image/jpeg',// 'png' => 'image/png',// 'css' => 'text/css',// 'html' => 'text/html',// 'htm' => 'text/html',// 'txt' => 'text/plain',// 'xsl' => 'text/xml',// 'xml' => 'text/xml',// 'mpeg' => 'video/mpeg',// 'mpg' => 'video/mpeg',// 'avi' => 'video/x-msvideo',// 'movie' => 'video/x-sgi-movie',}