poi 3.8讀取excel表格
阿新 • • 發佈:2019-01-30
讀取excel表格是poi中一種常用的方式,一開始沒有基礎不會寫。後來慢慢查了一些,然後給自己也總結一些,想著以後會用到的。
這次用poi是3.8的版本。
本方法在main方法裡做個試驗。資料是自己普通建的一個表
public static void main(String[] args) {
try {
File excelFile = new File("D:/Excel.xlsx"); //匯入表SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");//日期格式化,方便後邊判斷
FileInputStream is = new FileInputStream(excelFile); //檔案流
Workbook workbook = WorkbookFactory.create(is); //這種方式 Excel 2003/2007/2010 都是可以處理的
int sheetCount = workbook.getNumberOfSheets();//獲得所有的工作薄
for (int s = 0; s < sheetCount; s++) {
Sheet sheet = workbook.getSheetAt(s); //獲得for迴圈裡的每一個表
int rowCount = sheet.getPhysicalNumberOfRows(); //獲取總行數
//遍歷每一行
for (int r = 0; r < rowCount; r++) {
Row row = sheet.getRow(r);
int cellCount = row.getPhysicalNumberOfCells(); //獲取總列數
//遍歷每一列
for (int c = 0; c < cellCount; c++) {
Cell cell = row.getCell(c);
int cellType = cell.getCellType();
String cellValue = null;
switch(cellType) {
case Cell.CELL_TYPE_STRING: //文字
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC: //數字、日期
if(DateUtil.isCellDateFormatted(cell)) {
cellValue = fmt.format(cell.getDateCellValue()); //日期型
}
else {
cellValue = String.valueOf(cell.getNumericCellValue()); //數字
}
break;
case Cell.CELL_TYPE_BOOLEAN: //布林型
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_BLANK: //空白
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_ERROR: //錯誤
cellValue = "錯誤";
break;
case Cell.CELL_TYPE_FORMULA: //公式
cellValue = "錯誤";
break;
default:
cellValue = "錯誤";
}
System.out.print(cellValue + " ");
}
System.out.println();
}
}
}
}
2017年2月20日專案用的是3.15穩定版本,所以很多舊版本的屬性都用不了了,所以慢慢整理下。