POI操作本地excel
public static void checkExcelVaild(File file) throws Exception {
if (!file.exists()) {
throw new Exception("檔案不存在");
}
if (!(file.isFile() && (file.getName().endsWith(EXCEL_XLS) || file.getName().endsWith(EXCEL_XLSX)))) {
throw new Exception("檔案不是Excel");
}
}
public static void main(String[] args) throws Exception {
String path = "demo.xlsx";
List<Object> list = new ArrayList<>();
try {
// 同時支援Excel 2003、2007
File excelFile = new File(path); // 建立檔案物件
FileInputStream in = new FileInputStream(excelFile); // 檔案流
checkExcelVaild(excelFile);
Workbook workbook = WorkbookFactory.create(in); // 這種方式
Sheet sheet = workbook.getSheetAt(0); // 遍歷第一個Sheet
Object o = new Object();
for (Row row : sheet) {
for (int i = 0; i < row.getLastCellNum(); i++) {
Cell cell = row.getCell(i);
int cellType = cell.getCellType();
switch (cellType) {
case 0:
o = cell.getNumericCellValue();
break;
case 1:
o = cell.getStringCellValue();
break;
case 2:
o = cell.getCellFormula();
break;
case 3:
o = "";
break;
case 4:
o = cell.getBooleanCellValue();
break;
default:
// cell.setCellType(1);
o = cell.getStringCellValue();
break;
}
//如果要修改笨本地的excel
/*cell.setCellValue("");
FileOutputStream excelFileOutPutStream = new FileOutputStream(path);// 寫資料到這個路徑上
workbook.write(excelFileOutPutStream);*/
list.add(o);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}