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;
        }
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM