Java利用Poi讀取excel并對所有類型進行處理
1.最近做了一個批量導(dǎo)入功能 , 然后發(fā)現(xiàn)poi讀取excel的日期類型會出現(xiàn)點問題 , 因為我的需求是需要區(qū)分出
yyyy/MM/dd ,HH:mm:ss ,yyyy/MM/dd HH:mm:ss
2.日期,數(shù)字的類型都是數(shù)值的, 所有需要對每一個進行區(qū)分
根據(jù)cell.getCellStyle().getDataFormat() 方法 可以得到excel 格子中的short類型的值 ,從斷點中得知
yyyy/MM/dd 格式的值是 14
HH:mm:ss 格式的值是 21
yyyy/MM/dd HH:mm:ss 格式的值是 22
double 和 Int 都是 0 (我都轉(zhuǎn)成轉(zhuǎn)成String 再去做進一步處理)
下面是代碼可以把值寫成常量定義
public static String getCellValue(Cell cell) {
String cellValue = "";
if (cell == null) {
return cellValue;
}
// 判斷數(shù)據(jù)的類型
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: // 數(shù)字
//short s = cell.getCellStyle().getDataFormat();
if (HSSFDateUtil.isCellDateFormatted(cell)) {// 處理日期格式、時間格式
SimpleDateFormat sdf = null;
// 驗證short值
if (cell.getCellStyle().getDataFormat() == 14) {
sdf = new SimpleDateFormat("yyyy/MM/dd");
} else if (cell.getCellStyle().getDataFormat() == 21) {
sdf = new SimpleDateFormat("HH:mm:ss");
} else if (cell.getCellStyle().getDataFormat() == 22) {
sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
} else {
throw new RuntimeException("日期格式錯誤!!!");
}
Date date = cell.getDateCellValue();
cellValue = sdf.format(date);
} else if (cell.getCellStyle().getDataFormat() == 0) {//處理數(shù)值格式
cell.setCellType(Cell.CELL_TYPE_STRING);
cellValue = String.valueOf(cell.getRichStringCellValue().getString());
}
break;
case Cell.CELL_TYPE_STRING: // 字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: // Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: // 公式
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK: // 空值
cellValue = null;
break;
case Cell.CELL_TYPE_ERROR: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知類型";
break;
}
return cellValue;
}到此這篇關(guān)于Java利用Poi讀取excel并對所有類型進行處理的文章就介紹到這了,更多相關(guān)Java Poi讀取excel內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java mysql數(shù)據(jù)庫并進行內(nèi)容查詢實例代碼
這篇文章主要介紹了Java mysql數(shù)據(jù)庫并進行內(nèi)容查詢實例代碼的相關(guān)資料,需要的朋友可以參考下2016-11-11
Java實現(xiàn)將CSV轉(zhuǎn)為Excel的示例代碼
CSV(Comma?Separated?Values)文件是一種純文本文件,包含用逗號分隔的數(shù)據(jù),常用于將數(shù)據(jù)從一個應(yīng)用程序?qū)牖驅(qū)С龅搅硪粋€應(yīng)用程序。本文將利用Java實現(xiàn)CSV轉(zhuǎn)為Excel,感興趣的可以了解一下2022-03-03
java編寫創(chuàng)建數(shù)據(jù)庫和表的程序
這篇文章主要為大家詳細介紹了java編寫創(chuàng)建數(shù)據(jù)庫和表的程序,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10

