POI版本:3.5beat(前面的版本只能操作2003,不兼容2007)
1. Jar包導入項目lib文件夾下.
2. 創建ExcelOperation類:
package test;
//imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
public class ExcelIO {
/**
*讀取Excel
*/
public static String readExcel() throws IOException{
/**
*POI提供了對2003和2007的訪問接口,分別是HSSFWorkbook和XSSFWorkbook
*為了兼容2003和2007,這里選擇它們的共同接口,而不是自己的具象類
*切記,是org.apache.poi.ss.usermodel下的接口,
*不是org.apache.poi.hssf.model下的具象類
*/
Workbook wk = null; //Excel對象
Sheet sheet = null; //表對象
Row row = null; //行對象
Cell cell = null; //單元格對象
try {
//d盤根目錄有一個123.xslx的Excel文檔,先讀2007,如果出現異常
//就是2003,在進行2003的處理
wk = new XSSFWorkbook("D:/123.xlsx");// 2007
}catch (Exception ex) {
try {
//2003的對象需要一個輸入流
wk = new HSSFWorkbook(new FileInputStream("D:/123.xls"));// 2003
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//獲取第一張表
sheet =wk.getSheetAt(0);
//獲取第一行
row=sheet.getRow(0);
//獲取第一個單元格
cell=row.getCell(0);
/**
*單元格中不同的數據類型,讀取的方法也不同
*例如:字符類型使用getStringCellValue();
*數字類型使用getNumericCellValue()---返回double;
*其他數據類型的操作方法參考API,這里只做入門級別的操作..
*/
//String value=cell.getStringCellValue();
String value=cell.getNumericCellValue()+"";
/**
*下面是進行對數據的修改,但是一修改,Excel就打不開了.不清楚為什么,有待研究...
*/
//RichTextString text=null;
//text=new XSSFRichTextString("update");
//cell.setCellValue(text);
//cell.setCellValue("update");
//FileOutputStream fileOut = new FileOutputStream("D:/123.xlsx");
//wk.write(fileOut);fileOut.close();
return value;
}
public static void main(String[] args) {
try {
System.out.println(readExcel());
} catch (IOException e) {
e.printStackTrace();
}
}
}