码迷,mamicode.com
首页 > 数据库 > 详细

struts2+bootstrap-fileinput+poi 实现读取excel文件到数据库

时间:2016-11-28 19:46:25      阅读:388      评论:0      收藏:0      [点我收藏+]

标签:解析   man   ida   exception   ++   data   后台   cell   boot   

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

}

 

struts2+bootstrap-fileinput+poi 实现读取excel文件到数据库

标签:解析   man   ida   exception   ++   data   后台   cell   boot   

原文地址:http://www.cnblogs.com/staticxy/p/6110521.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!