1、模板下載
(1)模板的存儲位置:WEB-INF/file/fund.xlsx
(2)下載方法:
/**
* 下載方法
* @param path
* @param id
* @param req
* @return
*/
public static ResponseEntity<byte[]> download(String path, HttpServletRequest req) {
logger.info("【文件下載】 download --> 執行開始,請求文件相對路徑:" + path);
File file = null;
try {
// Resource resource = new ClassPathResource(path);
// file = resource.getFile();
// file=new File("c:/1.xlsx");
Resource resource=new ServletContextResource(req.getServletContext(),path);
file = resource.getFile();
} catch (Exception e) {
logger.info("【文件下載】 download -->執行異常,無法加載到服務端文件,請求文件相對路徑:" + path, e);
return null;
}
String fileName = null;
try {
fileName = new String(file.getName().getBytes("utf-8"), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
logger.info("【文件下載】 download -->執行異常,無法解析服務端文件,請求文件相對路徑:" + path, e);
return null;
}
HttpHeaders header = new HttpHeaders();
header.setContentDispositionFormData("attachment", fileName);
header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
byte[] res = null;
try {
res = FileUtils.readFileToByteArray(file);
} catch (IOException e) {
logger.info("【文件下載】 download -->執行異常,解析服務端文件爲字節數組異常,請求文件相對路徑:" + path, e);
return null;
}
return new ResponseEntity<byte[]>(res, header, HttpStatus.CREATED);
}
(3)controller方法:
// 促銷方案批量導入——模板下載
@ResponseBody
@RequestMapping(value ="/promotion/excel_down", method = {RequestMethod.GET}, produces = "text/plain;charset=UTF-8")
public ResponseEntity<byte[]> downloadModel( HttpServletRequest req, ModelMap model) throws InterruptedException {
ResponseEntity<byte[]> download = null;
String path = "WEB-INF/file/fund.xlsx";
try {
download = ExcelUtils.download(path, req);
} catch (Exception e) {
logger.error("", e);
e.printStackTrace();
}
return download;
}
2、excel上傳
(1)前端jsp:
——css:
<style type="text/css">
.file {
position: relative;
background: #D0EEFF;
border: 1px solid #99D3F5;
border-radius: 4px;
padding: 6px 12px;
margin-right: 10px;
overflow: hidden;
color: #1E88C7;
text-decoration: none;
text-indent: 0;
line-height: 25px;
}
.file input {
position: absolute;
right: 0;
top: 0;
opacity: 0;
}
.file:hover {
background: #AADFFD;
border-color: #78C3F3;
color: #004974;
text-decoration: none;
}
#upfile {
width:100px;
height:25px;
}
</style>
——form塊:
<form method="POST" enctype="multipart/form-data" id="form1" action="${pageContext.request.contextPath}/admin/promotion/excel_import">
<a class='btn btn-success btn-sm mr10' href="javascript:toDown()">模板下載</a>
<a href="javascript:;" class="file"><i class="fa fa-upload" aria-hidden="true"></i> 選擇文件
<input type="file" id="upfile" name="upfile" value="" /> </a>
<button type="submit" class="btn btn-info" οnclick="return checkData()">提交</button>
</form>
——js:
// 模板下載
function toDown(){
window.location.href="${pageContext.request.contextPath}/admin/promotion/excel_down";
}
//JS校驗form表單信息
function checkData(){
var fileDir = $("#upfile").val();
var suffix = fileDir.substr(fileDir.lastIndexOf("."));
if("" == fileDir){
alert("選擇需要導入的Excel文件!");
return false;
}
if(".xls" != suffix && ".xlsx" != suffix ){
alert("選擇Excel格式的文件導入!");
return false;
}
return true;
}
(2)controller方法:
/** 促銷方案批量導入——批量導入
* 描述:通過傳統方式form表單提交方式導入excel文件
* @param request
* @throws Exception
*/
@RequestMapping(value="/promotion/excel_import",method = {RequestMethod.GET, RequestMethod.POST })
public String uploadExcel(HttpServletRequest request,ModelMap model) throws Exception {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
System.out.println("通過傳統方式form表單提交方式導入excel文件!");
try{
InputStream in =null;
List<List<Object>> listob = null;
MultipartFile file = multipartRequest.getFile("upfile");
if(file.isEmpty()){
throw new BusinessException("000024","文件不存在!");
}
in = file.getInputStream();
listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());
in.close();
//該處可調用service相應方法進行數據保存到數據庫中,現只對數據輸出
List<Map<String,Object>> list = new ArrayList<>();
for (int i = 0; i < listob.size(); i++) {
List<Object> lo = listob.get(i);
Map<String,Object> map = new HashMap<>();
map.put("promotionCode", String.valueOf(lo.get(0)));
map.put("promotionName", String.valueOf(lo.get(1)));
map.put("investType", String.valueOf(lo.get(2)));
map.put("preferType", String.valueOf(lo.get(3)));
map.put("startDate", String.valueOf(lo.get(4)));
map.put("endDate", String.valueOf(lo.get(5)));
map.put("tradeMethod", String.valueOf(lo.get(6)));
map.put("fundCompCode", String.valueOf(lo.get(7)));
map.put("fundCode", String.valueOf(lo.get(8)));
map.put("rateValue", String.valueOf(lo.get(9)));
map.put("checkUser",getSessionUser());
map.put("modifyUser",getSessionUser());
list.add(map);
}
Map<String,Object> map = new HashMap<>();
map.put("list", list);
Client.send(Values.url_promotion_excelImport, map);
} catch (BusinessException e) {
Map<String,Object> param = new HashMap<>();
String result = Client.send(Values.url_promotion_PageList, param);
Map<String, Object> resultMap = JacksonUtils.json2map(result);
Map<String, Object> dataMap = ActionUtils.castMap(
resultMap.get("data"), Object.class);
model.addAttribute("list", dataMap.get("list"));
model.addAttribute("pageSize", SystemContext.getPagesize());
model.addAttribute("total", dataMap.get("total"));
model.addAllAttributes(param);
logger.error("", e);
//操作異常時需要將頁面數據放入model中
this.putMsg(model, e);
return "/fundbase/promotion/list";
} catch (Exception e){
logger.error("", e);
}
return "redirect:/admin/success?backUrl="
+ ActionUtils.toLink("/admin/promotion/browse");
}
以上就是spring mvc的excel模板下載和上傳的方法了,後面的涉及到數據分析層的邏輯,就不在這裏展示了,希望能幫助到大家,謝謝!