导入POI依赖:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency>HTMl:
<button type="button" id="downloadTemplate" style="background-color: #00D2FF" class="layui-btn">下载站点模板</button>JS:
//下载模板 $("#downloadTemplate").click(function () { location.href = perfix + "/downloadTemplate";//给后台controller路径就行 });
代码:
public void template(HttpServletResponse response) { //标题 首行列标题 String[] titles = {"xxxx", "xxxx", "xxx"}; //文件名 //如果需要2007以前的.xls 就直接改为 xxxx.xls String fileName = "xxxx.xlsx"; //sheet名 String sheetName = "sheet名字"; HSSFWorkbook hwb = new HSSFWorkbook(); //创建一个sheet HSSFSheet sheet = hwb.createSheet(sheetName); //创建第一行 HSSFRow row = sheet.createRow(0); //创建一个居中格式 HSSFCellStyle style = hwb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //创建列对象 HSSFCell cell = null; //创建绘图对象 绘图对象可以设置批注 HSSFPatriarch drawingPatriarch = sheet.createDrawingPatriarch(); for (int i = 0; i < titles.length; i++) { //获取批注对象 HSSFComment comment = drawingPatriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 7, 8)); //创建行 cell = row.createCell(i); //给第一行的每一列的单元格设置值 cell.setCellValue(titles[i]); if (i == 0) { //设置批注内容 comment.setString(new HSSFRichTextString("必填项,且名称唯一不重复")); } if (i == 1) { //设置批注内容 comment.setString(new HSSFRichTextString("必填项,且保证地址的正确性和具体位置")); } if (i == 2) { //设置批注内容 comment.setString(new HSSFRichTextString("非必填")); } //设置一个居中样式 里面有很多样式可以去看官方文档 cell.setCellStyle(style); //把批注设置到个单元格中 cell.setCellComment(comment); sheet.setColumnWidth(i, 256 * 30); } /** * 这段是设置单元格的下拉值 类似于下拉框 * @param */ List<String> carTypeList = getCarTypeList(); String[] carTs = carTypeList.toArray(new String[carTypeList.size()]); CellRangeAddressList regions = new CellRangeAddressList(1, 65535, 2, 2); DVConstraint constraint = DVConstraint.createExplicitListConstraint(carTs); HSSFDataValidation dataValidate = new HSSFDataValidation(regions, constraint); sheet.addValidationData(dataValidate); sheet.setColumnWidth(2, 256 * 25); //set些输出属性 try { try { fileName = new String(fileName.getBytes(), "ISO8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } response.setContentType("application/octet-stream;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); response.addHeader("Pargam", "no-cache"); response.addHeader("Cache-Control", "no-cache"); } catch (Exception ex) { ex.printStackTrace(); } //获取输出流 ServletOutputStream outputStream = null; try { outputStream = response.getOutputStream(); hwb.write(outputStream); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }