JavaWeb中如何导出Excel

来源:互联网 发布:不履行网络安全法 编辑:程序博客网 时间:2024/06/01 08:24

如何在JavaWeb中导出Excel

代码自解释

1,依赖包

<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.16</version></dependency>


2,编写Controller ,参考点击打开链接

@RequestMapping("/export")public void export(HttpServletRequest request, HttpServletResponse response) {// @See http://www.cnblogs.com/dingjiaoyang/p/5831049.htmlresponse.setContentType("application/vnd.ms-excel");response.setHeader("Content-disposition", "attachment;filename=myExcel.xls");OutputStream ouputStream = null;HSSFWorkbook wb = exportData();try {ouputStream = response.getOutputStream();wb.write(ouputStream);} catch (Exception e) {throw new RuntimeException("系统异常");} finally {try {ouputStream.flush();ouputStream.close();} catch (Exception e) {throw new RuntimeException("系统异常");}}}

3,Excel文件数据

private HSSFWorkbook exportData() {// 创建工作空间HSSFWorkbook wb = new HSSFWorkbook();// 创建表HSSFSheet sheet = wb.createSheet("mySheet");sheet.setDefaultColumnWidth(20);sheet.setDefaultRowHeightInPoints(20);// 创建行HSSFRow row = sheet.createRow((int) 0);// 生成一个样式HSSFCellStyle style = wb.createCellStyle();style.setAlignment(HorizontalAlignment.CENTER);// 水平居中style.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中// 背景色style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.YELLOW.getIndex());style.setFillPattern(FillPatternType.SOLID_FOREGROUND);style.setFillBackgroundColor(HSSFColor.HSSFColorPredefined.YELLOW.getIndex());// 设置边框style.setBorderBottom(BorderStyle.THIN);style.setBorderLeft(BorderStyle.THIN);style.setBorderRight(BorderStyle.THIN);style.setBorderTop(BorderStyle.THIN);// 生成一个字体HSSFFont font = wb.createFont();font.setFontHeightInPoints((short) 10);font.setColor(HSSFColor.HSSFColorPredefined.RED.getIndex());font.setBold(true);font.setFontName("宋体");// 把字体 应用到当前样式style.setFont(font);// 添加表头数据String[] excelHeader = { "row1", "row2", "row3" };for (int i = 0; i < excelHeader.length; i++) {HSSFCell cell = row.createCell(i);cell.setCellValue(excelHeader[i]);cell.setCellStyle(style);}// 添加单元格数据for (int i = 0; i < 3; i++) {row = sheet.createRow(i + 1);row.createCell(0).setCellValue("line" + i + ":row" + 1);row.createCell(1).setCellValue("line" + i + ":row" + 2);row.createCell(2).setCellValue("line" + i + ":row" + 3);}return wb;}



原创粉丝点击