读取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稳定版本,所以很多旧版本的属性都用不了了,所以慢慢整理下。