Java导出Excel(有数据库导出代码)

/**
     * 导出
     * @param request
     * @param response
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value="vehicleMaintainExport.do")
    public void exportVehicleMaintain(HttpServletRequest request,
            HttpServletResponse response) throws Exception{
        
        String param = request.getParameter("param");
        JSONObject jsonObject = JSONObject.fromObject(param);
        
        VehicleMaintainVo vehicleMaintainVo = (VehicleMaintainVo) JSONObject.toBean(jsonObject, VehicleMaintainVo.class);
        String date = DateUtil.format(new Date(), DateUtil.YYYYMMDD);
        // 获取输出文件的名字
        String displayName = PropertiesManager.getProperty("export.vehicleMaintain.fileName")+date+".xls";
        response.setContentType("application/vnd.ms-excel");
        BufferedOutputStream out = null;
        // 进行转码,使其支持中文文件名
        response.addHeader("Content-Disposition", "attachment;filename="
                + new String(displayName.getBytes("UTF-8"), "iso-8859-1"));
        try {
            // 获取输出流
            out = new BufferedOutputStream(response.getOutputStream());
        } catch (FileNotFoundException e1) {
            log.error(e1);
        }
        // 获取表格的表头字段名称
        String gridHead = PropertiesManager.getProperty("export.vehicleMaintain.columnNames");
        // 获取字段变量的名字
        String fieldNames = PropertiesManager.getProperty("export.vehicleMaintain.fieldNames");
        // 创建Excel
        HSSFWorkbook wb = new HSSFWorkbook();
        // 生成工作薄sheet(包含头信息)
        HSSFSheet mainSheet = this.generateSheet(wb, displayName, gridHead);
        // 设置数据样式
        HSSFCellStyle normalDataStyle = wb.createCellStyle();
        normalDataStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        // 用户查询出来的总记录
        long total = this.getTotal();
        // 计算需要分批查询的次数
        int eachQuerySize = Integer.parseInt(PropertiesManager.getProperty("export.excel.book.maxSheet"));
        int no = (int) total / eachQuerySize + 1;
        vehicleMaintainVo.setPageSize((int) total);
        // 追加数据时,第几行
        int rowNum = 0;
        // 一行时,第几个单元格
        int num = 0;
        // 当前记录的数目
        int currentRecordNum = 0;
        int sheetNameIndex = 2;
        int maxRow = Integer.parseInt(PropertiesManager.getProperty("export.excel.sheet.maxRow"));
        for(int n=1;n<=no;n++){
            vehicleMaintainVo.setPage(n);
            Page page = vehicleMaintainService.pageQuery(vehicleMaintainVo);
            List<VehicleMaintain>list = (List<VehicleMaintain>) page.getRows();
            for(VehicleMaintain vm:list){
                vm.setDeleteFlag(vm.getDeleteFlag().equals("0")?"未删除":"已删除");
                if (currentRecordNum > maxRow) {
                    mainSheet = this.generateSheet(wb, displayName
                            + sheetNameIndex, gridHead);
                    sheetNameIndex++;
                    currentRecordNum = 0;
                    rowNum = 0;
                }
                currentRecordNum++;
                num = 0;
                HSSFRow row = mainSheet.getRow(1 + rowNum);
                if (row == null) {
                    row = mainSheet.createRow(1 + rowNum);
                }
                // Insert data
                for (String field : fieldNames.split(",")) {
                    HSSFCell cell = row.getCell(num);
                    if (cell == null) {
                        cell = row.createCell(num);
                    }
                    cell.setCellStyle(normalDataStyle);
                    Field f = VehicleMaintain.class.getDeclaredField(field);
                    f.setAccessible(true);
                    Object value = f.get(vm);

                    this.setCellValue(cell, value);
                    num++;
                }
                rowNum++;
            }
        }
        
        try {
            wb.write(out);
            out.flush();
        } catch (Exception e) {
            log.error(e);
        }finally{
            try {
                out.close();
                JCDFWebUtil.Log(request, "导出车辆安装维护,参数为:"+param);
            } catch (IOException e) {
                log.error(e);
            }
        }
    }
    
    /**
     * 获取sheet
     * 
     * @param wb
     * @param sheetName 表格工作薄的名字
     * @param gridHead 表格的表头字段名称
     * @return
     */
    private HSSFSheet generateSheet(HSSFWorkbook wb, String sheetName,
            String gridHead) {
        // 判断表头信息是否为空
        if (null == gridHead) {
            throw new RuntimeException("表头信息为空,无法导出!");
        }
        HSSFSheet mainSheet = wb.createSheet(sheetName);
        // 设置标题sheet信息的样式
        HSSFFont headFont = wb.createFont();
        headFont.setFontHeightInPoints((short) 20);
        headFont.setColor(HSSFFont.COLOR_RED);
        HSSFCellStyle headStyle = wb.createCellStyle();
        headStyle.setFont(headFont);

        // 设置头信息的样式
        HSSFFont titleFont = wb.createFont();
        titleFont.setFontHeightInPoints((short) 8);
        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        titleFont.setColor(HSSFFont.COLOR_NORMAL);
        HSSFCellStyle headerStyle = wb.createCellStyle();
        headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        headerStyle.setFont(titleFont);

        String[] gridList = gridHead.split(",");
        // 创建第一行
        HSSFRow headRow = mainSheet.createRow(0);

        // 在第一行中添加头信息数据
        int num = 0;
        for (int i = 0; i < gridList.length; i++) {
            String column = gridList[i];
            // 创建单元格
            HSSFCell headCell = headRow.createCell(num);
            HSSFRichTextString h = new HSSFRichTextString(column);
            headCell.setCellValue(h);
            headCell.setCellStyle(headerStyle);
            int columnWidth = 100;
            mainSheet.setColumnWidth(num, columnWidth * 30);
            num++;
        }
        return mainSheet;
    }
    
    
    private void setCellValue(HSSFCell cell, Object value) {
        if (value instanceof java.lang.String) {
            cell.setCellValue(new HSSFRichTextString(value.toString()));
        } else if (value instanceof java.lang.Number) {
            cell.setCellValue(Double.parseDouble(value.toString()));
        } else if (value instanceof java.lang.Boolean) {
            cell.setCellValue(Boolean.parseBoolean(value.toString()));
        } else if (value instanceof java.util.Date) {
            cell.setCellValue(DateUtil.format((Date) value,DateUtil.YYYY_MM_DD));
        } else {
            cell.setCellValue("");
        }
    }

 

posted @ 2017-04-28 10:27  龍清扬  阅读(2092)  评论(0编辑  收藏  举报