springmvc上傳並解析excel檔案
阿新 • • 發佈:2018-11-17
1.從jsp頁面提交上傳excel檔案
<script type="text/javascript"> jQuery(document).ready(function(){ jQuery("#templetId").click(function(){ var btn = $(this); btn.button('loading'); setTimeout(function () {btn.button('reset')}, 2000); var url="/cancelInsurance/gettemplet.do"; $("#getTemplet").attr("action",url); $("#getTemplet").submit(); }); }); <form:form id="getTemplet" action=""></form:form> <form:form id="cancelInfo" action="cancelInsuranceEdit.do" method="post" enctype="multipart/form-data"> <div class="control-group"> <div class="controls"> <label class="control-label">選擇退保檔案:</label> <input type="file" name="cancelFiles" id="cancelFiles" accept=".xls,.xlsx,application/vnd.ms-excel" class="required"/> <button class="btn btn-info" data-loading-text="loading..." id="templetId" type="button">點選下載退保模板</button> </div> </div><br/><br/><br/> <div> <input id="btnSubmit" class="btn btn-primary btn-large" type="submit" data-loading-text="loading..." value="確認退保" style="margin-left: 200px;width: 200px;"/> </div> </form:form>
其中,點選獲取模板訪問/cancelInsurance/gettemplet.do,獲取模板的java程式碼如下
@RequestMapping(value = "gettemplet", method = RequestMethod.POST) public void getTemplate(HttpServletRequest request, RedirectAttributes redirectAttributes, HttpServletResponse response) { OutputStream out = null; InputStream is = null; try { is = new BufferedInputStream(this.getClass().getResourceAsStream( "/templates/jdCancelInsurance.xls"));//找到專案中儲存的.xls檔案 ExcelUtil.setExcelResponse(response,"京東批量退保模板"); Map beans = Maps.newHashMap(); beans.put("loginName", UserUtils.getUser().getLoginName()); Workbook workbook = WriteExcel.write(is, beans); // 將內容寫入輸出流並把快取的內容全部發出去 out = response.getOutputStream(); workbook.write(out); out.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { } } } }
2.解析.xls檔案(controller),java程式碼如下
ReadExcels readExcel=new ReadExcels();
//解析excel,獲取客戶資訊集合。
List<CancleInsuranceInfo> customerList = readExcel.getExcelInfo(filename ,multipartFile);
3.工具類,java程式碼如下
public class ReadExcels { //總行數 private int totalRows = 0; //總條數 private int totalCells = 0; //錯誤資訊接收器 private String errorMsg; //構造方法 public ReadExcels(){} //獲取總行數 public int getTotalRows() { return totalRows;} //獲取總列數 public int getTotalCells() { return totalCells;} //獲取錯誤資訊 public String getErrorInfo() { return errorMsg; } /** * 驗證EXCEL檔案 * @param filePath * @return */ public boolean validateExcel(String filePath){ if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))){ errorMsg = "檔名不是excel格式"; return false; } return true; } public List<CancleInsuranceInfo> getExcelInfo(String fileName,MultipartFile multipartFile){ //初始化退保資訊的集合 List<CancleInsuranceInfo> customerList=new ArrayList<CancleInsuranceInfo>(); //初始化輸入流 InputStream is = null; try{ //驗證檔名是否合格 if(!validateExcel(fileName)){ return null; } //根據檔名判斷檔案是2003版本還是2007版本 boolean isxls = true; if(WDWUtil.isxlsx(fileName)){ isxls = false; } //根據新建的檔案例項化輸入流 is = multipartFile.getInputStream(); //根據excel裡面的內容讀取客戶資訊 customerList = getExcelInfo(is, isxls); is.close(); }catch(Exception e){ e.printStackTrace(); } finally{ if(is !=null) { try{ is.close(); }catch(IOException e){ is = null; e.printStackTrace(); } } } return customerList; } /** * 根據excel裡面的內容讀退保資訊 * @param isxls excel是xls檔案還是xlsx檔案 * @return * @throws IOException */ public List<CancleInsuranceInfo> getExcelInfo(InputStream is,boolean isxls){ List<CancleInsuranceInfo> cancleInsuranceInfo=null; try{ /** 根據版本選擇建立Workbook的方式 */ Workbook wb = null; //當excel是xls時 if(isxls){ wb = new HSSFWorkbook(is); } else{//當excel是xlsx檔案時 wb = new XSSFWorkbook(is); } //讀取Excel裡面退保資訊 cancleInsuranceInfo=readExcelValue(wb); } catch (IOException e) { e.printStackTrace(); } return cancleInsuranceInfo; } /** * 讀取Excel裡面的資訊 * @param wb * @return */ private List<CancleInsuranceInfo> readExcelValue(Workbook wb){ //得到第一個shell Sheet sheet=wb.getSheetAt(0); //得到Excel的行數 this.totalRows=sheet.getPhysicalNumberOfRows(); //得到Excel的列數 if(totalRows>=1 && sheet.getRow(0) != null){ this.totalCells=sheet.getRow(0).getPhysicalNumberOfCells(); } List<CancleInsuranceInfo> cancleInsuranceInfos=new ArrayList<CancleInsuranceInfo>(); CancleInsuranceInfo cancleInsuranceInfo; //迴圈Excel行數,從第二行開始。標題不進行統計 for(int r=1;r<totalRows;r++){ Row row = sheet.getRow(r); if (row == null) continue; cancleInsuranceInfo = new CancleInsuranceInfo(); //迴圈取出Excel的列 for(int c = 0; c <this.totalCells; c++){ Cell cell = row.getCell(c); cell.setCellType(Cell.CELL_TYPE_STRING); if (null != cell){ if(c==0){//取出第一列 cancleInsuranceInfo.setServerNumber(cell.getStringCellValue()); }else if(c==4){//取出第五列 cancleInsuranceInfo.setBackCode(cell.getStringCellValue()); break; } } } //新增退保資訊 cancleInsuranceInfos.add(cancleInsuranceInfo); } return cancleInsuranceInfos; } }