导出

private void Export2Excel(String[] heads, String[] names,
            JSONArray jsonArray, HttpServletResponse response) {

        @SuppressWarnings("resource")
        Workbook workbook = new XSSFWorkbook();// 创建一个Excel文件
        
        Sheet sheet = workbook.createSheet();// 创建一个Excel的Sheet

        CellStyle style = workbook.createCellStyle();
//        HSSFColor
        style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());

        Row titleRow = sheet.createRow(0);

        for (int i = 0; i < heads.length; i++) {
            titleRow.createCell(i).setCellValue(heads[i]);
        }

        titleRow.setRowStyle(style);

        if (jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                Row row = sheet.createRow(i + 1);
                JSONObject json = jsonArray.getJSONObject(i); // 遍历 jsonarray
                for (int j = 0; j < names.length; j++) {
//                    instanceof 
                    Object temp=json.get(names[j]);
                    if(temp instanceof Double){
                        logger.info("==double:"+temp.toString());
                        row.createCell(j).setCellValue(
                                Double.parseDouble(temp.toString()));
                    }else{
                        row.createCell(j).setCellValue(
                                json.get(names[j]).toString());
                    }
                    

                }

            }
        }

        try {
            String mimetype = "application/x-msdownload";
            response.setContentType(mimetype);
            String downFileName = URLEncoder.encode("充电审计结果.xlsx", "UTF-8");
            String inlineType = "attachment"; // 是否内联附件
            response.setHeader("Content-Disposition", inlineType
                    + ";filename=\"" + downFileName + "\"");
            
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();        
            out.close();
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    

    

 

posted @ 2017-07-11 16:15  钟政123  阅读(277)  评论(0编辑  收藏  举报