这次在项目开发中,需要实现考题导出,由于本项目是使用spring Boot+AngularJS的开发模式,原来那种表单式的请求方式不是很便捷,以下是基于AngularJs异步请求的代码。
首先是JS代码
[javascript] view plain copy function exportExam() { $http({ url: url + "export", responseType: 'arraybuffer' }).success(function (res) { var blob = new Blob([res], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;"}); //var blob = new Blob([res], {type: "application/octet-stream"}); 这种类型的转换同样可行 saveAs(blob, "考题信息.xlsx"); }); } 这里需要注意三点:1、要在http的请求中将responseType设置为‘arraybuffer’类型,因为后台会将生成的excel转换成Byte数组并传送到前台2、经过博主测试,Blob的类型为以上两种都可以
3、为了更好的兼容浏览器,我们在这里使用了saveAs方法,这个方法是file-saver这个插件提供的
后台代码
[java] view plain copy public byte[] export(Integer[] idlist, int[] isoutput, String[] title) throws IOException { Map model = new HashMap(); model.put("excelName", "考题信息.xlsx"); model.put("sheetName", "sheet1"); model.put("title", title); if (idlist == null || idlist.length == 0) model.put("list", repo.findAll()); else { List<Integer> ids = new ArrayList<Integer>(); for (int i = 0; i < idlist.length; i++) ids.add(idlist[i]); model.put("list", repo.findAll(ids)); } model.put("isoutput", isoutput); XSSFWorkbook book = new XSSFWorkbook(); XSSFSheet sheet = book.createSheet(model.get("sheetName").toString()); XSSFRow header = sheet.createRow(0); // 产生标题列 int j = 0; for (int i = 0; i < title.length; i++) { if (isoutput[i] == 1) header.createCell(j++).setCellValue(title[i]); } int rowNum = 1; for (Exam exam : (List<Exam>) model.get("list")) { j = 0; XSSFRow row = sheet.createRow(rowNum++); if (isoutput[0] == 1) { row.createCell(j).setCellValue(exam.getTest()); j++; } if (isoutput[1] == 1) { row.createCell(j).setCellValue(exam.getOp1()); j++; } if (isoutput[2] == 1) { row.createCell(j).setCellValue(exam.getOp2()); j++; } if (isoutput[3] == 1) { row.createCell(j).setCellValue(exam.getOp3()); j++; } if (isoutput[4] == 1) { row.createCell(j).setCellValue(exam.getOp4()); j++; } if (isoutput[5] == 1) { row.createCell(j).setCellValue(exam.getAnswer()); j++; } if (isoutput[6] == 1) { row.createCell(j).setCellValue(exam.getTotal()); j++; } if (isoutput[7] == 1) { row.createCell(j).setCellValue(exam.gettotalCorrect()); j++; } if (isoutput[8] == 1) { row.createCell(j).setCellValue( (double) exam.gettotalCorrect() / exam.getTotal()); j++; } } ByteArrayOutputStream output = new ByteArrayOutputStream(); book.write(output); byte[] b = output.toByteArray(); return b; } 由于这部分代码经过各种修改,还没有整理好,这里大概说下思路。首先上半部分是查询后台数据并生成xlsx文件,也就是book对象;然后book.write方法将book转化为ByteArraryOutputStream,由于异步请求是通过Json来与前台交互的,因此不能直接传输ByteArraryOutputStream,所以有将它转换为byte数组。
以上是主要代码,经测试,该文件导出功能在Chrome、IE、猎豹浏览器中都能正常导出。
