POI 解析 excel

java操作Excel最常用的开源组件有poi与jxl。jxl是韩国人开发的,发行较早,但是更新的很慢,目前似乎还不支持excel2007。poi是apache下的一个子项目,poi应该是处理ms的office系列文档最好的组件了。poi3.7版本已经开始支持excel2007了。但是由于excel2007底层的实现似乎变成xml与excel2003底层存储发生了本质的变化,因此poi解析excel的类就存在差异了。
如需要接卸 xlsx 请参见 http://xiayingjie.iteye.com/blog/803682


import java.io.File;
import java.io.FileInputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class PoiReadXls2 {
	public static void main(String[] args) {
		File f = new File("c:\\c.xls");
		try {
			FileInputStream is = new FileInputStream(f);
			HSSFWorkbook wbs = new HSSFWorkbook(is);
			HSSFSheet childSheet = wbs.getSheetAt(0);
			System.out.println("有行数" + childSheet.getLastRowNum());
			for (int j = 0; j < childSheet.getLastRowNum(); j++) {
				HSSFRow row = childSheet.getRow(j);
				if (null != row) {
					for (short k = 0; k < row.getLastCellNum(); k++) {
						HSSFCell cell = row.getCell(k);
						if (null != cell) {
							switch (cell.getCellType()) {
							case HSSFCell.CELL_TYPE_NUMERIC: // 数字
								System.out.print(cell.getNumericCellValue()
										+ "   ");
								break;
							case HSSFCell.CELL_TYPE_STRING: // 字符串
								System.out.print(cell.getStringCellValue()
										+ "   ");
								break;
							case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
								System.out.println(cell.getBooleanCellValue()
										+ "   ");
								break;
							case HSSFCell.CELL_TYPE_FORMULA: // 公式
								System.out.print(cell.getCellFormula() + "   ");
								break;
							case HSSFCell.CELL_TYPE_BLANK: // 空值
								System.out.println(" ");
								break;
							case HSSFCell.CELL_TYPE_ERROR: // 故障
								System.out.println(" ");
								break;
							default:
								System.out.print("未知类型   ");
								break;
							}
						} else {
							System.out.print("-   ");
						}
					}
				}
				System.out.println();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

你可能感兴趣的:(Excel)