POI Workbook接口和HSSFWorkbook对象和XSSFWorkbook对象操作相应excel版本
由于HSSFWorkbook只能操作excel2003一下版本,XSSFWorkbook只能操作excel2007以上版本,所以利用Workbook接口创建对应的对象操作excel来处理兼容性
@Test
public void test6() throws Exception{
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream( new File("c://123.xls")));
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row =sheet.getRow(0);
HSSFCell cell= row.getCell(0);
System.out.println(cell.toString());
}
@Test
public void test7() throws Exception{
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream( new File("c://456.xlsx")));
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row =sheet.getRow(0);
XSSFCell cell= row.getCell(0);
System.out.println(cell.toString());
}
@Test //利用Workbook接口和判断excel版本创建相应版本HSSFWorkbook/XSSFWorkbook对象
public void test8() throws Exception{
String file = "c://456.xlsx";
boolean isExcel2003 = file.toLowerCase().endsWith("xls")?true:false;
Workbook workbook = null;
if(isExcel2003){
workbook = new HSSFWorkbook(new FileInputStream(new File(file)));
}else{
workbook = new XSSFWorkbook(new FileInputStream(new File(file)));
}
Sheet sheet = workbook.getSheetAt(0);
Row row =sheet.getRow(0);
Cell cell= row.getCell(0);
System.out.println(cell.toString());
}
感谢您的阅读,您的支持是我写博客动力。