Thứ Năm, 10 tháng 5, 2012

Read and Write excel file with POI library

Here is the simple code for reading and writing excel file with POI library

public void processExcel() throws FileNotFoundException {
        InputStream is = this.getClass().getResourceAsStream("/testpoi/ExcelFile.xls");
        FileInputStream fis = new FileInputStream("D://ExcelFile.xls");
        FileOutputStream fos = null;
        try {
            //HSSFWorkbook workbook = new HSSFWorkbook(is);
            HSSFWorkbook workbook = new HSSFWorkbook(fis);
            HSSFSheet sheet = workbook.getSheetAt(0);
            HSSFCell cell = null;
            int rows = sheet.getLastRowNum();
            //System.out.println("Total rows: " + rows);

            for (int i = 0; i < rows; i++) {
                double total = 0;
                for (int j = 0; j < 3; j++) {
                    cell = sheet.getRow(i + 1).getCell(j);
                    if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK
                            || cell.getCellType() == HSSFCell.CELL_TYPE_ERROR) {
                        continue;
                    }
                    if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                        double value = cell.getNumericCellValue();
                        //System.out.println("Value: " + value);
                        total += value;
                    }
                }
                vtResult.add(total);
            }
           
            //out result
            for (int h = 0; h < vtResult.size(); h++) {
                cell = sheet.getRow(h + 1).getCell(3);
                cell.setCellValue(vtResult.get(h));
            }

            // write workbook
            fos = new FileOutputStream("e://output.xls");
            workbook.write(fos);
            fos.close();
            workbook = null;
        } catch (IOException ex) {
            Logger.getLogger(ExcelUtil.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                is.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

Không có nhận xét nào:

Đăng nhận xét