在controller層中使用poi讀取excel表格中的資料
需求:需要對一個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外掛對檔案留進行操作。