如何在JavaWeb中导出Excel
代码自解释
1,依赖包
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi</artifactId>
- <version>3.16</version>
- </dependency>
- @RequestMapping("/export")
- public void export(HttpServletRequest request, HttpServletResponse response) {
- // @See http://www.cnblogs.com/dingjiaoyang/p/5831049.html
- response.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;
- }