前端界面
通过点击导入弹出一个文本框下载导入的模板
直接进入代码实现环节:
前端部分添加导入按钮:
<a href="javascript:;" class="btn btn-primary radius professional_btn">导入</a>
导入的文本框
//导入 $(".professional_btn").click(function(){ var url = "${base}/a/team/importes";//<----写接口的地方 layer_show_closebut("导入题目",url,null,400,function(){ var param =WT.wt_serializeJSONObject("searchForm"); $("#wt_table_list").wtTable({postData:param}); }); })
上面图二的页面代码
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta http-equiv="Content-Type" content="multipart/form-data; charset=utf-8" /> <#include "/a/commons/top.ftl" /> <title></title> <style type="text/css"> .row { box-sizing: border-box; margin-right: 90px; } </style> </head> <body> <article class="page-container"> <div class="div1"> <div class="row cl"> <label class="form-label col-xs-4 col-sm-3" style="text-align: right;margin-top: 5px;"><span class="c-red">*</span>文件:</label> <div class="formControls col-xs-8 col-sm-9"> <input type="file" class="input-text" value="" id="file" name="file"> </div> </div> <div class="layer-footer" style="position: fixed; bottom: 0;background-color:#fff;width:100%;height:55px;margin-left:-21px;line-height: 43px;border-top: 1px solid #ddd;" > <input class="btn btn-primary radius " id="admin-user-save" type="button" value=" 确定 " style="float: right;margin-right: 20px;margin-top: 10px;"> <input class="btn btn-primary radius " id="admin-user-don" type="button" value=" 下载模板 " style="float: right;margin-right: 10px;margin-top: 10px;"> <input class="btn btn-default radius " id="admin-user-colse" type="button" value=" 取消 " style="float: right;margin-right: 10px;margin-top: 10px;"> </div> </div> </article> <#include "/a/commons/bottom.ftl" /> <script type="text/javascript"> $(function() { $("#admin-user-save").click(function () { if(!formValidate()){ return; } WT.wt_confirm('是否导入?', function () { var formData = new FormData(); formData.append("file",$('#file')[0].files[0]); $.ajax({ url: '${base}/a/team/importteam', type: 'POST', data: formData, contentType: false, processData: false, success: function (data) { if(data.code == 0){ window.parent.exportData(data.msg); WT.wt_close(); }else{ layer.msg(data.msg); } }, error: function (data) { layer.msg(data.msg); } }); /*WT.wt_ajax_jsonobject('${base}/a/questions/importQuestion',formData, function(data) { if(data.code == 0){ window.parent.exportData("导入成功!"); WT.wt_close(); } });*/ }); }); $("#admin-user-don").click(function () { window.location.href = "/a/file/s/dev/teames.xls"; }); $("#admin-user-colse").click(function () { WT.wt_close(); }); }); function formValidate() { if (!$("#file").val().trim()) { WT.wt_msg('请选择文件!'); return false; } else { var suffix = ''; try { var flieArr = $("#file").val().split('.'); suffix = flieArr[flieArr.length - 1]; } catch (err) { suffix = ''; } if (!suffix) { WT.wt_msg('请选择excel的文件!'); return false; } var result = ['xls', 'xlsx'].indexOf(suffix.toLocaleLowerCase()) !== -1; if (!result) { WT.wt_msg('请选择excel的文件!'); return false; } return true; } } </script> </body> </html>
后端部分:
private static String TEMP_PATH = System.getProperty("java.io.tmpdir");
先通过get请求访问以上页面代码
//导入
@GetMapping("importes")
public String c(Model model) {
return "a/team/team_admin_importes";
/**
* 导入题目
* @param file
* @param request
* @return
*/
@PostMapping("/importteam")//这里就是上面绿色背景前端代码通过post请求这个接口
public @ResponseBody Map<String, Object> importteam(@ApiParam(required = true) @RequestBody @RequestParam MultipartFile file, HttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>();
if(file == null) {
map.put("code", 1);
map.put("msg", "文件为空");
return map;
}
File tempFile = null;
try {
String fileUuid = UUID.randomUUID().toString().replaceAll("-", "");
String fileName = fileUuid + "." + StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
tempFile = new File(TEMP_PATH + File.separator + fileName);
file.transferTo(tempFile);
DecimalFormat format = new DecimalFormat("#");
ExcelImportUtils ie = new ExcelImportUtils();
List<List<Object>> list = ie.read(tempFile);
if(list == null || list.size() < 1) {
map.put("code", 1);
map.put("msg", "文件为空");
return map;
}
System.out.println(list.size());
//excel第一行为标题
for(int i = 1; i < list.size(); i++) {
AccountDetailIO ques = new AccountDetailIO();
//这个AccountDetailIO io对应的是你新增接口的io,等一下要进行调用新增接口的
List<Object> cellList = list.get(i);
//题干
//专业
ques.setRealname(cellList.get(0).toString());
//这是读取第二行第一列的excel值
String certNum = cellList.get(3).toString();//这是读取第二行第四列的excel值,因为我这个值是一串长数字,会被以科学计算法显示,下面的方法就可以避免.
if(certNum!=null) {
String aaa = new BigDecimal(certNum).stripTrailingZeros().toString();
if (aaa.contains("E")) {
aaa = format.format(new BigDecimal(aaa));
ques.setCertNum(aaa);
}else{
ques.setCertNum(aaa);
}
System.out.println(aaa+"12121212");
}
ques.setRemark(cellList.get(5).toString());
//下面再调取新增接口,导入就完成了
authService.saveTeam(ques);
map.put("code", 0);
map.put("msg", "导入成功");
}
} catch (Exception e) {
e.printStackTrace();
map.put("code", 1);
map.put("msg", "文件为空");
} finally {
if(tempFile != null) {
tempFile.delete();
}
}
return map;
}
//导入工具类
public class ExcelRenderUtil {
private final static String CONTENT_TYPE = "application/msexcel;charset=utf-8";
private List<?>[] data;
private String[][] headers;
private String[] sheetNames = new String[]{};
private int cellWidth;
private String[] columns = new String[]{};
private String fileName = "file.xls";
private int headerRow;
private String version;
protected String view;
protected HttpServletRequest request;
protected HttpServletResponse response;
public ExcelRenderUtil(HttpServletRequest request, HttpServletResponse response, List<?>[] data) {
this.request = request;
this.response = response;
this.data = data;
}
public static ExcelRenderUtil me(HttpServletRequest request, HttpServletResponse response, List<?>... data) {
return new ExcelRenderUtil(request, response, data);
}
public void render() {
response.reset();
response.setHeader("Content-disposition", "attachment; " + FileRenderUtil.encodeFileName(this.request, fileName));
response.setContentType(CONTENT_TYPE);
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.addHeader("Access-Control-Allow-Headers", Constants.kAuth_xAccessToken);
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
OutputStream os = null;
try {
os = response.getOutputStream();
PoiExporter.data(data).version(version).sheetNames(sheetNames).headerRow(headerRow).headers(headers).columns(columns)
.cellWidth(cellWidth).export().write(os);
} catch (Exception e) {
throw new RenderException(e);
} finally {
try {
if (os != null) {
os.flush();
os.close();
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
public ExcelRenderUtil headers(String[]... headers) {
this.headers = headers;
return this;
}
public ExcelRenderUtil headerRow(int headerRow) {
this.headerRow = headerRow;
return this;
}
public ExcelRenderUtil columns(String... columns) {
this.columns = columns;
return this;
}
public ExcelRenderUtil sheetName(String... sheetName) {
this.sheetNames = sheetName;
return this;
}
public ExcelRenderUtil cellWidth(int cellWidth) {
this.cellWidth = cellWidth;
return this;
}
public ExcelRenderUtil fileName(String fileName) {
this.fileName = fileName;
return this;
}
public ExcelRenderUtil version(String version) {
this.version = version;
return this;
}
}
导入模板你需要在D盘或其他盘建一个textFile文件夹下建一个dev文件夹存放excel模板,项目完成之后最好把模板传到服务器
完