Java 操作Excel(导出数据到Excel)

//主入口

 HashMap<String, Object> fileMap = getFileBuffer(list,getZiduanMap());
                    byte[] buffer = (byte[]) fileMap.get("buffer");      //文件流
                    String path = fileMap.get("path").toString();     //文件路径
                    String fileName = fileMap.get("fileName").toString();   //文件名


//生成excel标题

 public HashMap<String, String> getZiduanMap(){

        HashMap<String, String> ziDuan = new HashMap<String, String>();
        ziDuan.put("0,typeName", "类型");// 属性前边的数字代表字段的先后顺序。
        ziDuan.put("1,serial", "序列号");// 最好将源码中判别顺序的格式改为"序号-字段"。
        ziDuan.put("2,brand", "品牌");
        ziDuan.put("3,mode", "型号");
        ziDuan.put("4,captial", "固定资产编号");
        ziDuan.put("5,ip", "IP地址");
        ziDuan.put("6,useType", "用途");
        ziDuan.put("7,cpuno", "CPU(核)");
        ziDuan.put("8,cpunoVirtual", "可虚拟化CPU(核)");
        ziDuan.put("9,memory", "内存(GB)");
        ziDuan.put("10,memoryVirtual", "可虚拟化内存(GB)");


        ziDuan.put("11,responsibilityName", "责任人");
        ziDuan.put("12,departmentName", "部门");
        ziDuan.put("13,updator", "操作人");
        ziDuan.put("14,updatetime", "操作日期");
        return ziDuan;

    }


 // 获取excel的文件流
    protected HashMap<String, Object> getFileBuffer(List<?> list, HashMap<String, String> ziDuan) throws Exception {
        byte[] buffer = null;
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        HashMap<String, Object> map = new HashMap<String, Object>();
        try {
            HashMap<String, Object> data = new HashMap<String, Object>();
            data.put("listData", list);
            data.put("ziDuan", ziDuan);
            File newfile = objListToExcel(data);
            String path = newfile.getPath();
            String fileName = newfile.getName();
            fis = new FileInputStream(newfile);
            bos = new ByteArrayOutputStream();
            byte[] b = new byte[102400];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            buffer = bos.toByteArray();
            map.put("buffer", buffer);
            map.put("path", path);
            map.put("fileName", fileName);
            return map;
        }catch (Exception e) {
            throw e;
        }finally {
            try {
                fis.close();
                bos.close();
            }catch (IOException e) {
                log.error(e);
            }
        }
    }


 protected File objListToExcel(HashMap<String, Object> data) throws Exception {
        HashMap<String, String> ziDuan = (HashMap<String, String>) data.get("ziDuan");
        List<ServerBean> listData = (List<ServerBean>) data.get("listData");
        Object[] keys = ziDuan.keySet().toArray();
        String[] ziDuanKeys = new String[keys.length];
        for (int k = 0; k < keys.length; k++) {
            String temp = keys[k].toString();
            int xuHao = Integer.valueOf(temp.split(",")[0]);
            ziDuanKeys[xuHao] = temp.split(",")[1];
        }
        OutputStream out = null;
        HSSFWorkbook wb = null;
        try {
            // String envirementPath =
            // PluginEnvirement.getInstance().getWorkDir();
            String fileName = "resource" + gerFileName() + ".xls";
            String envirementPath = "D:";
            String envirementPathName = envirementPath + "/" + fileName;
            File newFile = new File(envirementPathName);
            newFile.createNewFile();
            // System.out.println("创建文件成功");
            wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet();
            // 设置单元格字体
            HSSFFont font = wb.createFont();
            font.setFontHeightInPoints((short) 13);
            font.setFontName("微软雅黑");


            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            CellStyle cellStyle = wb.createCellStyle();
            cellStyle.setFont(font);


            for (int i = 0; i < listData.size() + 1; i++) {
                HSSFRow row = sheet.createRow(i);
                for (short j = 0; j < ziDuanKeys.length; j++) {
                    HSSFCell cell = row.createCell(j);
                    if (i == 0) {
                        sheet.setColumnWidth(j, (short) 6000);
                        cell.setCellStyle(cellStyle);
                        cell.setCellValue(new HSSFRichTextString(ziDuan.get(j + "," + ziDuanKeys[j])));
                    }else {


                        Object obj = listData.get(i - 1);
                        String ziDuanName = ziDuanKeys[j];
                        ziDuanName = ziDuanName.replaceFirst(ziDuanName.substring(0, 1), ziDuanName.substring(0, 1).toUpperCase());
                        ziDuanName = "get" + ziDuanName;
                        Method m = obj.getClass().getMethod(ziDuanName);
                        Object shuXing = m.invoke(obj);
                        if (shuXing != null) {
                            // System.out.print(shuXing.toString() + " ");
                            cell.setCellValue(shuXing.toString());
                        }else {
                            cell.setCellValue("");
                        }
                        break;
                    }
                }
            }


            out = new FileOutputStream(envirementPathName);
            wb.write(out);// 写入File
            out.flush();
            return newFile
        }catch ( Exception e)
        {
            throw e;
        }finally
        {
            try {
                wb.close();
                out.close();
            }catch (IOException e) {
                log.error(e);
            }
        }


    }




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值