来个poi(excel)实例

来源:互联网 发布:陈肇雄 网络强国 编辑:程序博客网 时间:2024/06/11 21:03

读取:

private void readDoc() {
        FileInputStream in = null;
        try {
            in = new FileInputStream(filterFile);
            HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(in));
            HSSFSheet sheet = wb.getSheetAt(0);

//在读取部分数据时建议用iterator查询,避免一次性加载过多的数据.

            Iterator<HSSFRow> it = sheet.iterator();

            while (it.hasNext()) {
                HSSFRow row = it.next();

                HSSFCell cell = row.getCell(0);
                String number = cell.getRichStringCellValue().getString().trim();

                cell = row.getCell(1);
                String pass = cell.getRichStringCellValue().getString().trim().substring(1);

                map.put(number, pass);
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                in.close();
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

 

创建:

private void writeDoc() {
        FileOutputStream out = null;
        HSSFWorkbook wb = null;
        try {
            out = new FileOutputStream("/home/hjglddok/1.xls");
            wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet("result");

            HSSFRow row = sheet.createRow(0);
                    HSSFCell cell = row.createCell(0);
                    cell.setCellValue(new HSSFRichTextString("你好"));

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                wb.write(out);
                out.close();
                ins.close();
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }