需求:需要对一个Excel表格中的数据,批量添加到数据库中
1.首先在JSP页面中可以写出来,选择文件的按钮,
<!--批量导入-->
<div id="dgBatchImport" class="easyui-dialog" title="批量导入文件" width="1100px" height="500px" closed="true" buttons="#dlgBatchImport-buttons" style="padding:10px" modal="true">
<form method="post">
<div align="left" style="margin-left: 10px">
<table id="tbBatchImport">
<tr><td>浏览文件:<input type="file" data-options="required:true, missingMessage:'点击选择图片'" id="blackListFile" name="blackListFile" style="width: 200px;height: 24px;">
<a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-add" onclick="importBlackGrey()">黑灰名单导入</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-print" onclick="exportResult()">导出结果</a>
</td></tr><tr><td></td></tr>
<tr><td>
<a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-add" onclick="confirmImport()">确认导入</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-print" onclick="cancle()">取消导入</a>
</td></tr>
</table>
</div>
<table id="dlgBatchImport" class="easyui-datagrid" singleSelect="false" fitColumns="true" nowrap="false" striped="true" SelectOnCheck="true" CheckOnSelect="true" rownumbers="true" toolbar="#tb">
<thead>
<tr>
<th field="blackValue" width="9%" align="center">加黑值</th>
<th field="blackType" width="9%" align="center">加黑类型</th>
<th field="blackReasonParentClass" width="10%" align="center">加黑原因父类</th>
<th field="blackReasonSonClass" width="9%" align="center">加黑原因子类</th>
<th field="ohterBlackReason" width="9%" align="center">其它加黑原因</th>
<th field="effect" width="9%" align="center" formatter="showEffect">效力</th>
<th field="dataSource" width="9%" align="center">数据来源</th>
<th field="sourceChannel" width="9%" align="center">来源渠道</th>
<th field="effectiveTime" width="9%" align="center" formatter="showEffectiveTime">生效时间</th>
<th field="status" width="9%" align="center" formatter="showStatus">状态</th>
<th field="remark" width="9%" align="center">备注</th>
</tr>
</thead>
</table>
<div align="center" style="margin-left: 10px">
<tr><td>
导入黑灰名单总数:<span id="blackGreyTotal" name="blackGreyTotal"></span>
导入成功数:<span id="successTotal" name="successTotal"></span>
导入失败数:<span id="failTotal" name="failTotal"></span>
导入重复数:<span id="repeatNumber" name="repeatNumber"></span>
</td></tr>
</div>
</form>
</div>
2.而后,将传入页面的JSP文件通过JS代码将流对象传递到controller中,本次实例采用的是ajax无刷新上传,将表单的内容提取出来采用ajax提交并且由前端决定请求结果回转后显示结果不用想表单提交那样跳转页面或者刷新页面,在这里采用jquery来操作DOM和ajax提交的js库
下面简单写一个小例子,体会一下,
前端页面中代码:
<form>
<input id="file" name="file" type="file" />
<input id="token" name="token" type="hidden" />
</form>
接下来通过JS代码将上传文件转换为二进制文件
JavaScript代码如下:
$("#file").on("change", function(){
var formData = new FormData();
formData.append("file", $("#file")[0].files);
formData.append("token", $("#token").val());
$.ajax({
url: "http://uploadUrl",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(response){
// 根据返回结果指定界面操作
}
});
});
在本次js代码中使用插件file的onchange函数来触发该事件,当然,也可以使用按钮,来触发事件,用到了formData对象来发送二进制文件,formData对象提供构造方法append()除了添加二进制参数还可以添加一些其他参数,如XMLHttpRequest的实例参数传给服务端
使用的jquery提供的ajax方法提交二进制文件还需要传递两个参数
processDate:false //不要对data参数进行序列化处理,默认为true
contextType:false //不要设置Content-Type请求头,因为请求头为multipart/formData来编码
下面是我使用在实战中的小例子
例子中JS代码,将二进制文件传入到controller
//黑灰名单导入
function importBlackGrey() {
if ($("#blackListFile").val() == "") {
$.messager.alert("信息", "需要选择一份Excel文件", "error");
return;
}
$.messager.confirm("确认","确认解析的Excel文件么", function (r) {
if (r) {
var formData = new FormData();
formData.append('file', $('#blackListFile')[0].files[0]);
formData.append('blackListFile', 0);
formData.append('isAll', true);
$.messager.progress({
title: "处理中",
msg: "正在解析..."
});
$("#dlgBatchImport").datagrid("loading");
$.ajax({
url: '/htm/blackListImport.htm',
type: 'POST',
cache: false,
data: formData,
async: false,
processData: false,
contentType: false,
success:function(data){
$.messager.progress("close");
$("#dlgBatchImport").datagrid("loadData", {"total":data.total, rows:data.pageData});
$("#dlgBatchImport").datagrid("loaded");
}
});
}
});
}
导入黑灰名单的excel文件时,会跳转到controller层
@RequestMapping(value = "/htm/blackListImport.htm",method = RequestMethod.POST)
@ResponseBody
public PagerModel<List<BlackGreyListResponseDto>> blackListImport(HttpServletRequest request) {
JsonModel json = new JsonModel();
json.setStatus(true);
Map<String, String> result = new LinkedHashMap<>();
PagerModel <List<BlackGreyListResponseDto>> pager = new PagerModel <>();
List<BlackGreyListResponseDto> dataList = null;
try {
if (request instanceof MultipartHttpServletRequest){
MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
Boolean isAll = mulRequest.getParameter("isAll") == null ? false : Boolean.parseBoolean(mulRequest.getParameter("isAll"));
List<MultipartFile> fileList = mulRequest.getFiles("file");
if (isAll && fileList.size() != 1) {
json.setStatus(false);
json.setMessage("请选择黑灰名单的Excel文件");
} else if (fileList.size() > 0) {
try (InputStream in = fileList.get(0).getInputStream()) {
Workbook wb = WorkbookFactory.create(in);
for (int i = 1; i < rownum; i++) {
BlackGreyListResponseDto blackGreyListResponseDto = new BlackGreyListResponseDto();
row = sheet.getRow(i);
if (row != null) {
blackGreyListResponseDto.setBlackValue(getCellFormatValue(row.getCell(0)));
blackGreyListResponseDto.setBlackType(Integer.valueOf(getCellFormatValue(row.getCell(1))));
blackGreyListResponseDto.setBlackReasonParentClass(Integer.valueOf(getCellFormatValue(row.getCell(2))));
blackGreyListResponseDto.setBlackReasonSonClass(Integer.valueOf(getCellFormatValue(row.getCell(3))));
blackGreyListResponseDto.setOtherBlackReason(getCellFormatValue(row.getCell(4)));
blackGreyListResponseDto.setEffect(getCellFormatValue(row.getCell(5)));
blackGreyListResponseDto.setDataSource(Integer.valueOf(getCellFormatValue(row.getCell(6))));
blackGreyListResponseDto.setSourceChannel(getCellFormatValue(row.getCell(7)));
blackGreyListResponseDto.setEffectiveTime(Long.valueOf(getCellFormatValue(row.getCell(8))));
dataList.add(blackGreyListResponseDto);
} else {
continue;
}
}
}
}
}
} catch (Exception e) {
}
List<JSONObject> list = new ArrayList<>();
Long count = 0L;
pager.setPageData(dataList);
pager.setTotal(Long.valueOf(dataList.size()));
return pager;
}
其中比较关键的一步就是将ServletHttpRequest请求转换为MultipartHttpServletRequest,不过在这之前需要进行一个判断,看是否传入的ServletHttpRequest可以转换为MultipartHttpServlet,如果能转换成功,那么就会继续执行,接下来就是使用poi插件对文件留进行操作。