java獲取excel中資料並存入資料庫表中
1--獲取excel檔案檔案所在路徑
由於公司的平臺框架封裝比較嚴重,獲取路徑方法可能略有不同,不必太放心上。
//獲取平臺附件配置檔案附件存放路徑
String realPath = FrameData.getInstance().getConfigItem("eform-config","config","attach-path");
//獲取附件完整路徑
String saveFile = realPath+"/"+(String)((HashMap)list.get(0)).get("SAVEFILE");
2--建立讀取附件檔案IO流
FileInputStream file = new FileInputStream(saveFile);
3--建立工作簿物件並獲取sheet和行數
Workbook workbook= null;
由於HSSFWorkbook只能對03版xls格式excel處理,因此,此處我先獲取檔名字,根據檔名字尾判斷,將xls和xlsx分別處理
//獲取附件名稱
String fileName = (String)((HashMap)list.get(0)).get("SOURCEFILE");
//判斷xlsx或xls
if(fileName.endsWith(".xlsx") || fileName.endsWith(".XLSX")){
workbook = new XSSFWorkbook(file);
}else{
workbook = new HSSFWorkbook(file);
}
//關閉檔案流
file.close();
//獲取excel第一個sheet
Sheet sheet = workbook.getSheetAt(0);
//獲取Excel表格中資料的行數
i
4--for迴圈開始獲取單元格內容
for (int loop = 3; loop < num; loop++) {
// 取i第行
Row row = sheet.getRow(loop);
//若有空行繼續下一行(因為EXCEL有空行時報錯故加上此程式碼)
if(row == null || "".equals(row)){
num--;
continue;
}
//姓名
String username = toString(getCellValue(row.getCell(1)));
//單位
String company_name = toString(getCellValue(row.getCell(3)));
//部門
String deptname = toString(getCellValue(row.getCell(4)));
........
//執行insert語句往表中插入資料(儘量使用帶事物的方法插入,防止注入攻擊)
}
try{}catch{}finally()我給省略了,自己寫的時候加上,如果有需要finally中記得刪除原始檔
//處理空字串非法,去首尾空格
private String toString(String str) {
if (str == null || "".equals(str)) {
return "";
} else {
return str.trim();
}
}
//獲取excel資料時對資料型別的判定及處理
private String getCellValue(Cell cell) {
String cellValue = "";
if (cell == null)
return cellValue;
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue().trim();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
DecimalFormat df = new DecimalFormat("0");
cellValue = df.format(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA:
cellValue = cell.getCellFormula();
break;
default:
cellValue = "";
}
return cellValue;
}