Apache POI(Excel) 初探

工作需要,了解了下使用POI解析Excel的方法。虽然是抄抄,希望对大家有所帮助。

将我在官网上收集的资料贴一下。

快速入门,可以作为代码参考的,官网取名:忙碌的程序员入门

HOWTO系列,简单介绍了下怎么使用POI,讲到了两套不同的API,一套是user model,调用相对较简单,抽象比较高一点,占内存(memory footprint)大,另一套是event user model,抽象层次低,调用相对较复杂,占内存小,适合想要了解下Excel文件的同学。

另附上usermodel的类图,也是来自官网。

最后贴上一个简单的TestCase

public void testCellType(){
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("测试日期");
		HSSFRow row = sheet.createRow(0);
		HSSFCell cell0 = row.createCell(0);
		cell0.setCellValue("2012/12/25");
		printType(cell0);		
		HSSFCell cell1 = row.createCell(1);
		cell1.setCellValue(true);
		printType(cell1);		
		HSSFCell cell2 = row.createCell(2);
		cell2.setCellValue(12.5);
		printType(cell2);
		try {
			FileOutputStream fileOut = new FileOutputStream("D:/testDate.xls");
			wb.write(fileOut);
			fileOut.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param cell
	 */
	private void printType(HSSFCell cell) {
		switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
            	System.out.println("string");
                System.out.println(cell.getRichStringCellValue().getString());
                break;
            case Cell.CELL_TYPE_NUMERIC:
            	System.out.println("numeric");
                if (DateUtil.isCellDateFormatted(cell)) {
                    System.out.println(cell.getDateCellValue());
                } else {
                    System.out.println(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
            	System.out.println("boolean");
                System.out.println(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA:
            	System.out.println("formula");
                System.out.println(cell.getCellFormula());
                break;
            default:
                System.out.println();
        }

	}
}

  

posted on 2012-11-08 16:58  livewall  阅读(537)  评论(0)    收藏  举报

导航