匯入工具包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(); }
}