struts2+bootstrap-fileinput+poi 实现读取excel文件到数据库
//js代码
function initUpload(){ $("#uploadfile").fileinput({ language: 'zh', //设置语言 uploadUrl: $("body").attr("data-url")+"/permission/roleUpload!upload.action", //上传的地址 allowedFileExtensions: ['xls', 'xlsx'],//接收的文件后缀 //uploadExtraData:{"id": 1, "fileName":'123.mp3'}, uploadAsync: true, //默认异步上传 showUpload: true, //是否显示上传按钮 showRemove : true, //显示移除按钮 showPreview : true, //是否显示预览 showCaption: false,//是否显示标题 browseClass: "btn btn-primary", //按钮样式 dropZoneEnabled: false,//是否显示拖拽区域 //minImageWidth: 50, //图片的最小宽度 //minImageHeight: 50,//图片的最小高度 //maxImageWidth: 1000,//图片的最大宽度 //maxImageHeight: 1000,//图片的最大高度 //maxFileSize: 0,//单位为kb,如果为0表示不限制文件大小 //minFileCount: 0, maxFileCount: 10, //表示允许同时上传的最大文件个数 enctype: 'multipart/form-data', validateInitialCount:true, previewFileIcon: "<i class='glyphicon glyphicon-king'></i>", msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!", }); }
jsp代码
<!-- 文件上传 -->
<label class="control-label">请选择要导入的Excel文件:</label>
<input type="file" name="uploadFiles" id="uploadfile" class="file-loading" />
<s:fielderror></s:fielderror>
后台action代码
public String upload(){ String savePath=ServletActionContext.getServletContext().getRealPath("/static/upload/"); File uploadDir=new File(savePath); if(!uploadDir.exists()){ uploadDir.mkdirs(); } SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd"); String ymd=sdf.format(new Date()); savePath+="/"+ymd+"/"; File dirFile=new File(savePath); if(!dirFile.exists()){ dirFile.mkdirs(); } if(this.uploadFiles!=null){ for(int i=0;i<uploadFiles.size();i++){ String fileExt=uploadFilesFileName.get(i).substring(uploadFilesFileName.get(i).lastIndexOf(".")+1).trim().toLowerCase(); List<String>arr=Arrays.asList(extMap.split(",")); if(!arr.contains(fileExt)){ super.addActionError(this.uploadFilesFileName.get(i)+"文件类型错误!只允许"+extMap+"格式。"); continue; } SimpleDateFormat sdfForFileName=new SimpleDateFormat("yyyyMMddHHmmss"); String newName=sdfForFileName.format(new Date())+"_"+new Random().nextInt(1000)+"."+fileExt; File destFile=new File(dirFile,newName); try { FileUtils.copyFile(uploadFiles.get(i), destFile); List<List<String>>roles=ExcelUtil.readXlsx(savePath+newName); for(List<String> row:roles){ Role role=new Role(); role.setRoleName(row.get(1)); rolebiz.insert(role); } } catch (Exception e) { super.addActionError(this.uploadFilesFileName.get(i)+"上传失败!"+e.getMessage()); continue; } } } System.out.println("保存路径:"+savePath); return SUCCESS; }
后台POI解析excel代码
public class ExcelUtil { public static List<List<String>> readXlsx(String path){ List<List<String>> result=new ArrayList<List<String>>(); try { InputStream input=new FileInputStream(path); 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); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } public static List<List<String>> readXls(String path){ List<List<String>> result=new ArrayList<List<String>>(); try { InputStream input=new FileInputStream(path); 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); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } 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; } } }