1. 首先到官網把插件下載下來
git clone https://github.com/kartik-v/bootstrap-fileinput.git
2. 將文件導入到工程,在前端頁面將插件引入
<link rel="stylesheet" href="${basePath}/resources/plugs/bootstrap-fileinput/css/fileinput.min.css"/> <script src="${basePath}/resources/plugs/bootstrap-fileinput/js/fileinput.min.js"></script> <script src="${basePath}/resources/plugs/bootstrap-fileinput/js/locales/zh.js"></script>
3. 導入界面
<div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> <li class="fa fa-remove"></li> </button> <h5 class="modal-title">Excel文件上傳</h5> </div> <div class="modal-body"> <form id="importFile" name="importFile" class="form-horizontal" method="post" enctype="multipart/form-data"> <div class="box-body"> <div> <label class="control-label">請選擇要導入的Excel文件:</label> <input id="excelFile" name="excelFile" class="file-loading" type="file" multiple accept=".xls,.xlsx" > <br> </div> </div> </form> </div>
4. js處理
<script> initUpload("excelFile", basePath + "/test/upload"); function initUpload(ctrlName, uploadUrl) { var control = $('#' + ctrlName); control.fileinput({ language: 'zh', //設置語言 uploadUrl: uploadUrl, //上傳的地址 uploadAsync: true, //默認異步上傳 showCaption: true,//是否顯示標題 showUpload: true, //是否顯示上傳按鈕 browseClass: "btn btn-primary", //按鈕樣式 allowedFileExtensions: ["xls", "xlsx"], //接收的文件后綴 maxFileCount: 10,//最大上傳文件數限制 previewFileIcon: '<i class="glyphicon glyphicon-file"></i>', showPreview: true, //是否顯示預覽 previewFileIconSettings: { 'docx': '<i ass="fa fa-file-word-o text-primary"></i>', 'xlsx': '<i class="fa fa-file-excel-o text-success"></i>', 'xls': '<i class="fa fa-file-excel-o text-success"></i>', 'pptx': '<i class="fa fa-file-powerpoint-o text-danger"></i>', 'jpg': '<i class="fa fa-file-photo-o text-warning"></i>', 'pdf': '<i class="fa fa-file-archive-o text-muted"></i>', 'zip': '<i class="fa fa-file-archive-o text-muted"></i>', }, uploadExtraData: function () { var extraValue = "test"; return {"excelType": extraValue}; } }); } $("#excelFile").on("fileuploaded", function (event, data, previewId, index) { console.log(data); if(data.response.success == true) { alert(data.files[index].name + "上傳成功!"); //關閉 $(".close").click(); } else{ alert(data.files[index].name + "上傳失敗!" + data.response.message); //重置 $("#excelFile").fileinput("clear"); $("#excelFile").fileinput("reset"); $('#excelFile').fileinput('refresh'); $('#excelFile').fileinput('enable'); } }); </script>
5. 后台接口
@RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody private Result importExcel(@RequestParam(value = "excelFile", required = false) MultipartFile file,HttpServletRequest request) { try { MultipartRequest multipartRequest=(MultipartRequest) request; MultipartFile excelFile=multipartRequest.getFile("excelFile"); if(excelFile!=null){ List<List<String>> datas = ExcelUtil.readXls(excelFile.getInputStream()); //TODO: 讀到的數據都在datas里面,根據實際業務邏輯做相應處理
// ............. if(datas!=null && datas.size()>0){ return new Result(true); } }else{ return new Result(false); } } catch (Exception e) { return new Result(false,e.getMessage()); } return new Result(false); }
6. 附ExcelUtil類
package com.cnpc.framework.util; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public class ExcelUtil { public static List<List<String>> readXlsx(String path) throws IOException { InputStream input = new FileInputStream(path); return readXlsx(input); } public static List<List<String>> readXls(String path) throws IOException { InputStream input = new FileInputStream(path); return readXls(input); } public static List<List<String>> readXlsx(InputStream input) throws IOException { List<List<String>> result = new ArrayList<List<String>>(); XSSFWorkbook workbook = new XSSFWorkbook(input); for (XSSFSheet xssfSheet : workbook) { if (xssfSheet == null) { continue; } for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) { XSSFRow row = xssfSheet.getRow(rowNum); int minCellNum = row.getFirstCellNum(); int maxCellNum = row.getLastCellNum(); List<String> rowList = new ArrayList<String>(); for (int i = minCellNum; i < maxCellNum; i++) { XSSFCell cell = row.getCell(i); if (cell == null) { continue; } rowList.add(cell.toString()); } result.add(rowList); } } return result; } public static List<List<String>> readXls(InputStream input) throws IOException { List<List<String>> result = new ArrayList<List<String>>(); HSSFWorkbook workbook = new HSSFWorkbook(input); for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) { HSSFSheet sheet = workbook.getSheetAt(numSheet); if (sheet == null) { continue; } for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { HSSFRow row = sheet.getRow(rowNum); int minCellNum = row.getFirstCellNum(); int maxCellNum = row.getLastCellNum(); List<String> rowList = new ArrayList<String>(); for (int i = minCellNum; i < maxCellNum; i++) { HSSFCell cell = row.getCell(i); if (cell == null) { continue; } rowList.add(getStringVal(cell)); } result.add(rowList); } } return result; } private static String getStringVal(HSSFCell cell) { switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: return cell.getBooleanCellValue() ? "TRUE" : "FALSE"; case Cell.CELL_TYPE_FORMULA: return cell.getCellFormula(); case Cell.CELL_TYPE_NUMERIC: cell.setCellType(Cell.CELL_TYPE_STRING); return cell.getStringCellValue(); case Cell.CELL_TYPE_STRING: return cell.getStringCellValue(); default: return null; } } }