java-匯入
阿新 • • 發佈:2018-12-15
由於資料量很多,需要匯入這個功能。 需要注意的幾個地方 1.實體需要給每個欄位填加註釋:@ExcelVOAttribute(name = “公司名稱”, column = “A”)
@ExcelVOAttribute(name = "公司名稱", column = "A") private String companyName; @ExcelVOAttribute(name = "公司英文名稱", column = "B") private String enCompanyName; @ExcelVOAttribute(name = "招展代理", column = "C") private String exhibitorAgent;
與Excel表格相對應 2.前端jsp
$('#excelPath').change(function () { var excelPath = $("#excelPath").val(); if (excelPath == null || excelPath == '') { alert("請選擇要上傳的Excel檔案"); return; } else { var fileExtend = excelPath.substring(excelPath.lastIndexOf('.')).toLowerCase(); if (fileExtend == '.xls') { $("#upload").ajaxSubmit({ url: "${ctx}/exhibitor/oldcustomer/importOldExhibitorExcel.action", cache: false, dataType: 'json', success: function (ret) { console.log("匯入歷史展商返回結果:" + ret); layer.msg('匯入成功'); page(); $('#upload')[0].reset() }, error: function (ret) { layer.msg(ret.msg); alert("error"); $('#upload')[0].reset() } }); } else { alert("檔案格式需為'.xls'格式"); return; } } });
後端Controller
//匯入歷史展商資料 @RequestMapping(value = "/importOldExhibitorExcel", method = RequestMethod.POST) @ResponseBody public CommonStatus importOldExhibitorExcel(@RequestParam(value = "excelPath", required = false) MultipartFile file) { LOGGER.info("批量匯入歷史展商"); boolean isAllow = false; String fileName = file.getOriginalFilename(); int index = fileName.lastIndexOf("."); if (index < 0) { return faile("非法檔案"); } String suffux = fileName.substring(index); for (String s : WebConstant.ALLOW_IMPORT) { if (s.equals(suffux)) { isAllow = true; break; } } if (!isAllow) { return faile("非法檔案"); } try { FileInputStream fis = (FileInputStream) file.getInputStream(); ExcelUtil<TOldCustomer> util = new ExcelUtil<TOldCustomer>(TOldCustomer.class); List<TOldCustomer> list = util.importExcel("Sheet1", fis); for (TOldCustomer c : list) { if (c == null) { continue; } boolean switchFlag = false; String url = PropertyPlaceholder.getProperty("domain"); String path = PropertyPlaceholder.getProperty("img_dir"); } for (int i = 0; i < list.size(); i++) { TOldCustomer oldCustomer = list.get(i); oldCustomerService.insertSelective(oldCustomer); } } catch (IOException e) { LOGGER.info("匯入excel異常e={}", e); } String path = request.getSession().getServletContext().getRealPath("positionexcel"); SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/"); String urlnew = sdf.format(new Date()); fileName = urlnew + fileName; File targetFile = new File(path, fileName); if (!targetFile.exists()) { targetFile.mkdirs(); } // 儲存 try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); LOGGER.error("儲存檔案失敗e=", e); } return success("匯入成功"); }
4.同時用到了Excel工具類,ExcelUtil.java
public List<T> importExcel(String sheetName, InputStream input) {
int maxCol = 0;
List<T> list = new ArrayList<T>();
try {
HSSFWorkbook workbook = new HSSFWorkbook(input);
HSSFSheet sheet = workbook.getSheet(sheetName);
if (!sheetName.trim().equals("")) {
sheet = workbook.getSheet(sheetName);// 如果指定sheet名,則取指定sheet中的內容.
}
if (sheet == null) {
sheet = workbook.getSheetAt(0); // 如果傳入的sheet名不存在則預設指向第1個sheet.
}
int rows = sheet.getPhysicalNumberOfRows();
if (rows > 0) {// 有資料時才處理
// Field[] allFields = clazz.getDeclaredFields();// 得到類的所有field.
List<Field> allFields = getMappedFiled(clazz, null);
Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();// 定義一個map用於存放列的序號和field.
for (Field field : allFields) {
// 將有註解的field存放到map中.
if (field.isAnnotationPresent(ExcelVOAttribute.class)) {
ExcelVOAttribute attr = field.getAnnotation(ExcelVOAttribute.class);
int col = getExcelCol(attr.column());// 獲得列號
maxCol = Math.max(col, maxCol);
// System.out.println(col + "====" + field.getName());
field.setAccessible(true);// 設定類的私有欄位屬性可訪問.
fieldsMap.put(col, field);
}
}
for (int i = 1; i < rows; i++) {// 從第2行開始取資料,預設第一行是表頭.
HSSFRow row = sheet.getRow(i);
// int cellNum = row.getPhysicalNumberOfCells();
// int cellNum = row.getLastCellNum();
int cellNum = maxCol;
T entity = null;
//System.err.println("cellNum="+cellNum);
for (int j = 0; j <= cellNum; j++) {
//System.err.println("j="+j);
if (row==null) {
continue;
}
HSSFCell cell = row.getCell(j);
if (cell == null) {
continue;
}
int cellType = cell.getCellType();
String c = "";
Integer val;
//System.err.println("cellType="+cellType);
if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
val=(int)cell.getNumericCellValue();
c = String.valueOf(val);
} else if (cellType == HSSFCell.CELL_TYPE_BOOLEAN) {
c = String.valueOf(cell.getBooleanCellValue());
} else {
c = cell.getStringCellValue();
}
//System.err.println("c="+c);
if (c == null || c.equals("")) {
continue;
}
entity = (entity == null ? clazz.newInstance() : entity);// 如果不存在例項則新建.
// System.out.println(cells[j].getContents());
Field field = fieldsMap.get(j);// 從map中得到對應列的field.
if (field == null) {
continue;
}
// 取得型別,並根據物件型別設定值.
Class<?> fieldType = field.getType();
//System.err.println("fieldType="+fieldType.toString());
if (String.class == fieldType) {
field.set(entity, String.valueOf(c));
} else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
field.set(entity, Integer.valueOf(c));
} else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {
field.set(entity, Long.valueOf(c));
} else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {
field.set(entity, Float.valueOf(c));
} else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) {
field.set(entity, Short.valueOf(c));
} else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {
field.set(entity, Double.valueOf(c));
} else if (Character.TYPE == fieldType) {
if ((c != null) && (c.length() > 0)) {
field.set(entity, Character.valueOf(c.charAt(0)));
}
}else{
System.out.println("未知的欄位資料型別fieldType="+fieldType.getClass().toString());
}
}
if (entity != null) {
list.add(entity);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return list;
}