思路: 后台读取数据库 ---> 填充到Excel表格 ---> Excel表格存储到临时文件夹 ---> 从临时文件夹下载
jsp代码
<a class="btn btn-primary" type="button" id="download-excel">Download Excel Menu</a> JavaScript代码 $('#download-excel').click(function(){ $.ajax({ url: 'createTempExcel', type: 'post', dataType: 'json', success: function(data){ if(data.status == 'fail'){ alert('error'); }else{ window.location.href = "downloadExcel?fileName="+data.fileName; } } }); });
@RequestMapping(value = "/createTempExcel", method = RequestMethod.POST, produces = "application/json; charset=utf-8") @ResponseBody public Map<String, Object> createTempExcel(HttpServletRequest request) { Map<String, Object> result = new HashMap<String, Object>(); // --- 数据库读取数据 存储到Excel保存到临时文件夹 --- String tempPath = request.getServletContext().getInitParameter("tempPath"); File dir = new File(tempAbsolutePath); if (!dir.exists()) { dir.mkdirs(); } String fileName = new Date().getTime() ++ ".xlsx"; List<Document> docs = new ArrayList<Document>(); //--- docs 填充数据库的数据 --- result = ExcelXSSFUtils.createExcel(docs, tempAbsolutePath, fileName); if (result.get("status").equals("fail")) { return result; } result.put("fileName", fileName); return result; } @RequestMapping(value = "/downloadExcel") public void downloadExcel(HttpServletRequest request, HttpServletResponse response) throws IOException { String fileName = request.getParameter("fileName"); String tempPath = request.getServletContext().getInitParameter("tempPath"); // --- 从临时文件夹下载 --- response.setHeader("content-disposition", "attachment;filename=xxx.xlsx"); response.setContentType("application/octet-stream; charset=utf-8"); FileInputStream in = new FileInputStream(tempAbsolutePath + fileName); OutputStream out = response.getOutputStream(); byte buffer[] = new byte[1024]; int len = 0; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } in.close(); out.close(); }
/** * * * @param data * 数据库数据 * @param tempPath * 临时文件夹路径 * @param fileName * 文件名 * @return */ public static Map<String, Object> createExcel(List<Document> data, String tempPath, String fileName) { Map<String, Object> result = new HashMap<String, Object>(); String[] textList = { "true", "false" }; XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); XSSFRow row = null; XSSFCell cell = null; // --- rowHeader --- row = sheet.createRow(0); cell = row.createCell(0); //-- 类似设置header --- // --- 数据有效性 下拉框选择 --- DataValidationHelper helper = new XSSFDataValidationHelper((XSSFSheet) sheet); XSSFDataValidationConstraint constraintBoolean = new XSSFDataValidationConstraint(textList); CellRangeAddressList regionsBoolean = new CellRangeAddressList(1, 500, 6, 11); DataValidation validationBoolean = helper.createValidation(constraintBoolean, regionsBoolean); validationBoolean.createErrorBox("输入值有误", "请从下拉框选择"); validationBoolean.setShowErrorBox(true); sheet.addValidationData(validationBoolean); // --- 数据有效性 只允许输入整数 --- DataValidationConstraint constraintNum = new XSSFDataValidationConstraint( DataValidationConstraint.ValidationType.INTEGER, DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "0"); CellRangeAddressList regionNumber = new CellRangeAddressList(1, 500, 4, 5); DataValidation validationNum = helper.createValidation(constraintNum, regionNumber); validationNum.createErrorBox("输入值类型出错", "数值型,请输入大于或等于0的整数值"); validationNum.setShowErrorBox(true); sheet.addValidationData(validationNum); // --- 数据有效性 只允许输入小数 --- DataValidationConstraint constraintDecimal = new XSSFDataValidationConstraint( DataValidationConstraint.ValidationType.DECIMAL, DataValidationConstraint.OperatorType.GREATER_OR_EQUAL, "0"); CellRangeAddressList regionDecimal = new CellRangeAddressList(1, 500, 3, 3); DataValidation validationDecimal = helper.createValidation(constraintDecimal, regionDecimal); validationDecimal.createErrorBox("输入值类型出错", "数值型,请输入大于或等于0的小数值"); validationDecimal.setShowErrorBox(true); sheet.addValidationData(validationDecimal); for (int i = 0; i < menuItems.size(); i++) { XSSFCellStyle cellStyle = wb.createCellStyle(); XSSFColor xssfColor = new XSSFColor(); Document item = menuItems.get(i); // --- get cell value --- String code = data.getString("code"); String color = "FF" + (item.getString("color") != null ? item.getString("color").substring(1, item.getString("color").length()) : "FFFFFF"); //--- 以下是从该数据库data获取的数据 --- xssfColor.setARGBHex(color); cellStyle.setFillForegroundColor(xssfColor); cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); cellStyle.setBorderBottom(CellStyle.BORDER_THIN); // 下边框 cellStyle.setBorderLeft(CellStyle.BORDER_THIN);// 左边框 cellStyle.setBorderTop(CellStyle.BORDER_THIN);// 上边框 cellStyle.setBorderRight(CellStyle.BORDER_THIN);// 右边框 // --- insert cell value --- row = sheet.createRow(i + 1); cell = row.createCell(0); cell.setCellStyle(cellStyle); cell.setCellValue(code); } FileOutputStream out; try { out = new FileOutputStream(tempPath + fileName); wb.write(out); out.close(); } catch (FileNotFoundException e) { result.put("status", "fail"); result.put("message", "Database Error."); return result; } catch (IOException e) { result.put("status", "fail"); result.put("message", "Database Error."); return result; } result.put("status", "success"); return result; }