导入工具包ImportExcelUtils
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.joda.time.DateTime;
import java.io.FileInputStream;
import java.util.Date;
public class ImportExcelUtils {
public void cellType(FileInputStream inputStream) throws Exception {
//创建工作簿
//03版,excel后缀为.xls的,07版本为.xlsx的,需要将HSSFWorkbook()更换为XSSFWorkbook()
Workbook workbook = new HSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);//获取第一页
//获取标题内容
Row rowTitle = sheet.getRow(0);
if (rowTitle != null){
int cellCount = rowTitle.getPhysicalNumberOfCells();//获取列的数量
for (int cellNum = 0; cellNum < cellCount ; cellNum++) {
Cell cell = rowTitle.getCell(cellNum);
if (cell != null){
int cellType = cell.getCellType();//获取列的类型
}
}
}
//读取表中内容
int rowCount = sheet.getPhysicalNumberOfRows();
for (int rowNum = 1; rowNum < rowCount; rowNum++) {
Row rowData = sheet.getRow(rowNum);
if (rowData != null){
//读取列
int cellCount = rowData.getPhysicalNumberOfCells();
for (int cellNum = 0; cellNum < cellCount ; cellNum++) {
Cell cell = rowData.getCell(cellNum);
if (cell != null){
int cellType = cell.getCellType();
String cellValue = "";
//判断列数据类型
switch (cellType){
case HSSFCell.CELL_TYPE_STRING://字符串
cellValue = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN://布尔
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_BLANK://空
break;
case HSSFCell.CELL_TYPE_NUMERIC://数字(日期、数字)
if (HSSFDateUtil.isCellDateFormatted(cell)){//日期
Date date = cell.getDateCellValue();
cellValue = new DateTime(date).toString("yyyy-MM-dd");
}else{
//防止数字过长
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cellValue = cell.toString();
}
break;
case HSSFCell.CELL_TYPE_ERROR://错误
break;
}
}
}
}
}
//关闭流
inputStream.close();
}
}