SpringMvc 上傳excel(註解和非註解兩種方式)
阿新 • • 發佈:2019-01-08
1、第一種方式:
A:JSP頁面:
<form name="importForm" action="${ctx }/service/userService/BatchImport.do" method="post" enctype="multipart/form-data">
請選擇上傳所需檔案:<input type="file" id="theFile" name="theFile" /><br/>
<input type="submit" value="提交"/>
</form>
B: Controller 層
@Controller
@RequestMapping("/service/userService")
public class LoadUserServiceAction {
@Reference
UserHelper userHelper;
@Reference
ClassHelper classHelper;
@Reference
InstitutionHelper institutionHelper;
@RequestMapping("/BatchImport")
public void BatchImport(HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
PrintWriter pw = null;
request.setCharacterEncoding("utf-8");
int roleID = NumberUtils.toInt(request.getParameter("role"));
int organID = NumberUtils.toInt(request.getParameter("organ" ));
//是否忽略警告
boolean ignoreWarning = BooleanUtils.toBoolean(request.getParameter("ignore"));
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile importFile = multipartRequest.getFile("theFile");
try {
JSONObject json = new JSONObject();
json.put("needConfirm", false);
pw = response.getWriter();
if(importFile == null){
json.put("error", "未讀取到檔案");
pw.print(json.toString());
}else{
Workbook workbook = null;
String fileName = importFile.getOriginalFilename();
if(StringUtils.isNotBlank(fileName)){
String[] strArr = fileName.split("\\.");
if(strArr != null && strArr.length > 0){
if("xls".equals(strArr[strArr.length - 1])){
workbook = new HSSFWorkbook(importFile.getInputStream());
} else if("xlsx".equals(strArr[strArr.length - 1])){
workbook = new XSSFWorkbook(importFile.getInputStream());
} else {
json.put("error", "無法讀取的檔案格式");
pw.print(json.toString());
}
}
}
StringBuilder errorReason = new StringBuilder();
if(organID < 0){
json.put("error", "讀取不到正確的機構id");
pw.print(json.toString());
}
List<Object[]> objsArrList = readExcel(workbook, organID, roleID);
boolean needConfirm = checkData(objsArrList, roleID, errorReason);
if(errorReason.length() > 0 &&
( (needConfirm && ! ignoreWarning) || !needConfirm )){
json.put("needConfirm", needConfirm);
json.put("error", errorReason.toString().replaceAll("\\[|]", ""));
pw.print(json.toString());
}
userHelper.saveUserObjects(objsArrList);
pw.print("success");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(pw != null){
pw.flush();
pw.close();
}
}
}
/**
* 檢查資料
* @param objsArrList 物件陣列
* @param errorReason 錯誤原因
*/
private boolean checkData(List<Object[]> objsArrList, int roleID, StringBuilder errorReason){
//這是省略了檢驗資料的程式碼。。。。
}
/**
* 讀取excel並且形成物件
* @param workbook 工作簿物件
* @return
*/
private List<Object[]> readExcel(Workbook workbook, int organID, int roleID){
List<Object[]> objsArr = new ArrayList<Object[]>();
//得到工作簿開始解析資料
Sheet sheet = workbook.getSheetAt(0);
//處理資料
}
}
2、採用註解的方式接受jsp傳過來的檔案
A: jsp 頁面不變
B: Controller 層
其實和上面差不多 主要的區別就是在方法裡添加了引數,該引數採用註解的方式,前提條件是要求引數名和jsp中的檔案的name值必須一致,否則得到的是null;
具體程式碼:
@Controller
@RequestMapping("/service/userService")
public class LoadUserServiceAction {
@Reference
UserHelper userHelper;
@Reference
ClassHelper classHelper;
@Reference
InstitutionHelper institutionHelper;
@RequestMapping("/BatchImport")
public void BatchImport(MultipartFile theFile,HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
PrintWriter pw = null;
request.setCharacterEncoding("utf-8");
int roleID = NumberUtils.toInt(request.getParameter("role"));
int organID = NumberUtils.toInt(request.getParameter("organ"));
//是否忽略警告
boolean ignoreWarning = BooleanUtils.toBoolean(request.getParameter("ignore"));
//theFile拿到的就是該檔案,然後進行相應的操作
//和上面的一樣
}
}
純手工作業,轉摘的時候請附上我的url。謝謝