您的位置:首页 > 其它

poi 3.10 读取excel(2003/2007)

2014-03-09 11:03 302 查看
public class TestExcel {
private static String filePath = "";
private static String version = "2003";//默认为2003版本
private static Workbook wb = null;
private static Sheet sheet = null;
static User user = new User();

public static void setVersion(String filePath){
if(filePath.endsWith(".xlsx")){
version = "2007";
}
}

public static Workbook getWorkbook() throws IOException, InvalidFormatException{
BufferedInputStream in = new BufferedInputStream(new FileInputStream(filePath));
if("2003".equals(version)){
POIFSFileSystem fs = new POIFSFileSystem(in);
wb = (Workbook)new HSSFWorkbook(fs);
}else if("2007".equals(version)){
wb = (Workbook)new XSSFWorkbook(in);
}
return wb;
}

public static void print(){
try {

wb = getWorkbook();
int sheets = wb.getNumberOfSheets();//获取sheet的数量
//			System.out.println(sheets);
sheet = wb.getSheetAt(0);//取第一个sheet
for(int i = sheet.getFirstRowNum()+1;i<sheet.getPhysicalNumberOfRows();i++){
Row row = sheet.getRow(i);
for(int j = row.getFirstCellNum();j<row.getPhysicalNumberOfCells();j++){
Cell cell = row.getCell(j);
//					System.out.println(cell.getCellStyle());//样式
//					cell.getCellType();//获得类型
/**
* CellType 类型 值
*	CELL_TYPE_NUMERIC 数值型 0
*	CELL_TYPE_STRING 字符串型 1
*	CELL_TYPE_FORMULA 公式型 2
*	CELL_TYPE_BLANK 空值 3
*	CELL_TYPE_BOOLEAN 布尔型 4
*	CELL_TYPE_ERROR 错误 5
*
*
* */
Object content = "";
if(cell.getCellType() == cell.CELL_TYPE_BLANK){
content = "";
}else if(cell.getCellType() == cell.CELL_TYPE_NUMERIC){
content = cell.getNumericCellValue();
}else if(cell.getCellType() == cell.CELL_TYPE_STRING){
content = cell.getStringCellValue();
}else if(cell.getCellType() == cell.CELL_TYPE_BOOLEAN){
content = cell.getBooleanCellValue();
}

System.out.println(content);
}
}
} catch (IOException e) {
System.out.println("读取文件失败。");
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String[] args) {
filePath = "d:"+File.separator+"workbook.xlsx";
setVersion(filePath);
print();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: