java操作生成Excel报表

课程设计中遇到需要生成报表,于是在网上搜集了相关资料。下面贴上实现后的代码。


首先,项目是maven项目。添加依赖。

<!-- 输出报表依赖 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>

controller:

/*
     * 根据传递的ID导出对应报表
     */
    @RequestMapping("/export/{id}")  
    public void export(HttpServletRequest request, HttpServletResponse response,@PathVariable("id")Integer id) {  
        response.setContentType("application/vnd.ms-excel");  
        response.setHeader("Content-disposition", "attachment;filename=myExcel.xls");  
        OutputStream ouputStream = null;  
        HSSFWorkbook wb = exportData(id);  
        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("系统异常");  
            }  
        }  
    }

    private HSSFWorkbook exportData(Integer id) {  
        //获取教师课表信息
        List<TeacherSubjectVO> tsByTeacherID = tsService.getTSByTeacherID(id);

        // 创建工作空间  
        HSSFWorkbook wb = new HSSFWorkbook();  
        // 创建表  
        HSSFSheet sheet = wb.createSheet("课程表");  
        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 = { "课程名", "学分", "上课时间","上课地点" };  
        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 <tsByTeacherID.size(); i++) {  
            row = sheet.createRow(i + 1);  
            row.createCell(0).setCellValue(tsByTeacherID.get(i).getsName());  
            row.createCell(1).setCellValue(tsByTeacherID.get(i).getsScore()); 
            //对日期单独处理
            Cell cell = row.createCell(2);
            cell.setCellValue(tsByTeacherID.get(i).getTsDate());
            CreationHelper createHelper = wb.getCreationHelper();  
            CellStyle cellStyle = wb.createCellStyle();  
            cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd"));  
            cell.setCellStyle(cellStyle); 

            row.createCell(3).setCellValue(tsByTeacherID.get(i).getTsAddr());  
        }  
        return wb;  
    }  

猜你喜欢

转载自blog.csdn.net/zwzsdy/article/details/80734959