package TestDemo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.*;
import java.text.SimpleDateFormat;
/**
* Created by LiuTao on 2017/3/13.
*/
public class Test {
/**
* 读取Excel文件的内容
* @param file
* @return
*/
public static boolean readExcel(File file) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
//文件流
FileInputStream is = new FileInputStream(file);
//这种方式 Excel 2003/2007/2010 都是可以处理的
Workbook workbook = WorkbookFactory.create(is);
//Sheet的数量
int sheetCount = workbook.getNumberOfSheets();
//遍历每个Sheet
for (int s = 0; s < sheetCount; s++) {
Sheet sheet = workbook.getSheetAt(s);
//获取总行数
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);
if (cell == null) {
continue;
}
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();
}
}
} catch (Exception e) {
return false;
}
return true;
}
public static void main(String[] args) {
File excelFile = new File("E://hello.xls"); //创建文件对象
readExcel(excelFile);
}
}
注意:在引用实现上面的读取功能的时厚需要添加相应的maven依赖。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.7</version>
</dependency>
代码运行后产生的结果:
测试表格
楼号 梯数 姓名 面积 单价 物业费 联系电话 备注
1# 1101.0 张三 90.0 0.4 521.0 13644527895 2012-01-21
2# 1102.0 李四 85.0 1.4 522.0 13644527896 2012-01-22
3# 1103.0 王五 90.0 2.4 523.0 13644527897 2012-01-23
4# 1104.0 刘六 120.0 3.4 524.0 13644527898 2012-01-24
5# 1105.0 赵七 100.0 4.4 525.0 13644527899 2012-01-25