在.xls;*.xlsx类型文件的导入(可以导入多条数据)

2018-11-28   17:36:35

需要jar包:poi-3.8-201203026.jar

jsp页面:

<LINK href="${basePath}plugins/uploadify/uploadify.css" type="text/css" rel="stylesheet" />
<script language="javascript" type="text/javascript">
    //防止客户端缓存文件,造成uploadify.js不更新,而引起的“喔唷,崩溃啦”  
    document.write ("<script type='text/javascript' " + "src='${basePath}plugins/uploadify/jquery.uploadify.min.js?" + new Date () + "'><\/script>");
</script>
<script type="text/javascript"> 
//导入excel $(function(){ $(
"#uploadFile").uploadify({ buttonClass:'', fileSizeLimit: '20480KB', uploader: '${basePath}core/upload!uploadFile.action', // 服务器端处理地址 swf: '${basePath}js/uploadify/uploadify.swf', // 上传使用的 Flash buttonText: "导入", buttonCursor: 'hand', fileObjName: 'uploadify',// 上传参数名称 后台action里面的属性uploadify fileTypeExts: "*.xls;*.xlsx", // 扩展名 fileTypeDesc: "请选择 文件格式", removeTimeout:1, // 文件说明 auto: true, // 选择之后,自动开始上传 multi: false, // 是否支持同时上传多个文件 queueSizeLimit: 1, // 允许多文件上传的时候,同时上传文件的个数 queueID:'queueID', onUploadSuccess:function(file, data, response){ var data =jQuery.parseJSON(data); if(data.error == 1){ ldDialog.alert(data.message); }else{ $.ajax({ url:"${basePath}uploadDocumentAction/uploadDocument!insertDrawWorkerMany.action", type:"post", dataType:"json", data:{filePath:data.url,fileName:data.newFileName,crId:"${crId}",dchId:"",chGxId:""}, async:false, success:function(r){ if(r.code=="success"){ ldDialog.tips ("导入成功!"); document.pagerForm.submit (); }else{ if(r.message!="" && r.message!=null){ ldDialog.tips (r.message,"5"); }else{ ldDialog.tips ("导入失败!"); } } } }); } } }); }); </script> <input type="button" id="uploadFile" class="ldBtnGray" value="导入"/> <a href="${basePath}upload/template/template11.xls" download="template11.xls">
<span style='float:right;margin-right:20px;margin-top:10px;font-size:18px;color:#2891d2;'>模板下载</span></a>

java类: core/upload!uploadFile.action

    @RequestMapping("core/upload!uploadFile.action")
    public void uploadFile(@RequestParam(value = "uploadify", required = false) MultipartFile uploadify,HttpServletRequest request,HttpServletResponse response,ModelMap modelMap) throws Exception {

        @SuppressWarnings("deprecation")
        String savePath = request.getRealPath("/")+ "/" + "upload/";
        String saveUrl = "upload/";
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("file", "pdf,rar,zip,7z,gif,jpg,jpeg,png,bmp,doc,docx,xlsx,xls");
        //extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("csv", "csv");
         int uploadMaxSize =Integer.valueOf(optionService.getByOptionName(CoreValue.OPTION_UPLOAD_MAX_SIZE).getOptionValue());
        long maxSize = Long.valueOf(String.valueOf(uploadMaxSize)).longValue();
        String maxSizeKb = StringUtil.formatNumber(new Double(maxSize / 1024L),"0");
        response.setContentType("text/html; charset=UTF-8");
        String jsonString = "";
        if (!ServletFileUpload.isMultipartContent(getRequest())) {
            jsonString = getError("请选择文件。");
            response.getWriter().println(jsonString);
            return;
        }

        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
            jsonString = getError(savePath + "上传目录不存在。");
            response.getWriter().println(jsonString);
            return;
        }

        if (!uploadDir.canWrite()) {
            jsonString = getError("上传目录没有写权限。");
            response.getWriter().println(jsonString);
            return;
        }

        String dirName = getRequest().getParameter("dir");
        if (dirName == null) {
            dirName = "file";
        }
        if (!extMap.containsKey(dirName)) {
            jsonString = getError("目录名不正确。");
            response.getWriter().println(jsonString);
            return;
        }

        savePath = savePath + dirName + "/";
        saveUrl = saveUrl + dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String ymd = sdf.format(new Date());
        savePath = savePath + ymd + "/";
        saveUrl = saveUrl + ymd + "/";
        File dirFile = new File(savePath);

        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        String fileName = uploadify.getOriginalFilename();
        long fileSize = uploadify.getSize();
        if (fileSize > maxSize) {
            jsonString = getError("上传文件大小超过限制。最大为" + maxSizeKb + "kb");
            response.getWriter().println(jsonString);
            return;
        }

        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            
        if (!Arrays.asList(((String) extMap.get(dirName)).split(",")).contains(fileExt)) {
            jsonString = getError("不允许的上传文件类型。");
            response.getWriter().println(jsonString);
            return;
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_"+ new Random().nextInt(1000) + "." + fileExt;
        File uploadedFile = null;
        try {
            uploadedFile = new File(savePath, newFileName);
            if(uploadedFile.exists()){
                
            }
            if(!uploadedFile.exists()){
                uploadedFile.mkdirs();
            }
            uploadify.transferTo(uploadedFile);
        } catch (Exception e) {
            jsonString = getError("上传文件失败。");
            response.getWriter().println(jsonString);
            return;
        }
        JSONObject obj = new JSONObject();
        obj.put("error", Integer.valueOf(0));
        obj.put("url", saveUrl + newFileName);
        obj.put("newFileName", newFileName);
        obj.put("fileName", fileName);
        jsonString = obj.toJSONString();
        response.getWriter().println(jsonString);
    }

    private String getError(String message) {
        JSONObject obj = new JSONObject();
        obj.put("error", Integer.valueOf(1));
        obj.put("message", message);
        return obj.toJSONString();
    }

 java类:uploadDocumentAction/uploadDocument!insertDrawWorkerMany.action

/** 设计编制工程量excel批量导入 */
    @ResponseBody
    @RequestMapping("uploadDocument!insertDrawWorkerMany.action")
    public JSONObject insertDrawWorkerMany(ModelMap modelMap, HttpServletRequest request) {

        String filePath = getStringParameter("filePath");
        String fileName = getStringParameter("fileName");
        String abPath = request.getSession().getServletContext().getRealPath("/");
        filePath = abPath + filePath;
        List<CompletedQuantityPo> batPos = new ReadInfoTableExcel().getExcelToGcl(filePath);
        String message = "";
        String strTemp = "";
        for (int i = 0; i < batPos.size(); i++) {
            CompletedQuantityPo completedQuantity = batPos.get(i);
            //校验文件中的数据类型:是数据类型的校验
            Pattern pattern = Pattern.compile("^([0-9]+(.[0-9]*))?|([0-9])?$");
            if(!(pattern.matcher(completedQuantity.getComNum()).matches())) {
                    message = "【数量】字段数据类型应该为数值,请修改!";
                    break;
            }
            strTemp = "success";
        }
        result.put("message", message);
        result.put("code", strTemp);
    }

方法:getExcelToGcl

  /**
     * 获取excel里的工程量基本信息
     * @param filepath
     * @param filetype
     * @param uuid
     * @return
     */
    public List<CompletedQuantityPo> getExcelToGcl(String filepath) {
            try{
                return addexcelToGclHSSF1(filepath);
            }catch (Exception e1){
                return null;
            }
        }
  
    /**
     * 批量导入需要方法
     * @param filepath
     * @return
     * @throws IOException
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     */
    public List<CompletedQuantityPo> addexcelToGclHSSF1(String filepath) throws IOException,NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        List<ZuobiaoInfo> zuobiaoInfos=new ArrayList<ZuobiaoInfo>();
        List<CompletedQuantityPo> batPos = new ArrayList<CompletedQuantityPo>();
        HSSFWorkbook xwb = new HSSFWorkbook(new FileInputStream(filepath));  
        HSSFSheet sheet= xwb.getSheetAt(0);
        zuobiaoInfos=new TableinfoTest().getTest11();
        int rowsnumber = this.getnumber(filepath);
        for(int i=1;i<rowsnumber+1;i++){
            boolean flag = true;
            CompletedQuantityPo batPo = new CompletedQuantityPo();
            for(int j=0 ;j<zuobiaoInfos.size();j++){
                Class c = batPo.getClass();
                Class[] cargs = new Class[1];
                int cellnumber= zuobiaoInfos.get(j).getZongzuobiao();
                try{
                    Object realArgs=this.getHSSFSheetExcelvalue(i, cellnumber, sheet);
                    if(null!=realArgs){
                        cargs[0] = realArgs.getClass();
                        String  method=zuobiaoInfos.get(j).getMethod();
                        if(!realArgs.toString().equals("")){
                            if(method!=null&&!method.equals("")){
                                Method m = c.getMethod(method, cargs);
                                Object[] inArgs = new Object[1];
                                inArgs[0] = realArgs;
                                m.invoke(batPo, inArgs);
                            }
                        }else{
                            flag = false;
                            break;
                        }
                    }
                }catch (Exception e){
                    //e.printStackTrace();
                    flag = false;
                    break;
                }
            }
            if(flag){
                batPos.add(batPo); 
            }
            
        }
        return batPos;
    }

方法:TableinfoTest().getTest11();

public class TableinfoTest {
 List<ZuobiaoInfo> test11 =new ArrayList<ZuobiaoInfo>
    (Arrays.asList(
        new ZuobiaoInfo("setQuotaNumber", "定额编号", 0),
        new ZuobiaoInfo("setProName", "项目名称", 1),
        new ZuobiaoInfo("setUnit", "单位", 2),
        new ZuobiaoInfo("setComNum", "数量", 3),
        new ZuobiaoInfo("setConsumptionCoefficient", "工日系数(单位定额值)", 4),
        new ZuobiaoInfo("setUnitMechanic", "技工(单位定额值)", 5),
        new ZuobiaoInfo("setUnitGeneralWorker", "普工(单位定额值)", 6),
        new ZuobiaoInfo("setMechanic", "技工(合计值)", 7),
        new ZuobiaoInfo("setGeneralWorker", "普工(合计值)", 8),
        new ZuobiaoInfo("setRemark", "备注", 9)
        ));

    public List<ZuobiaoInfo> getTest11() {
        return test11;
    }
}

方法:this.getnumber(filepath);

public int getnumber(String filepath)  {
    try{
        XSSFWorkbook xwb = new XSSFWorkbook(filepath);  
        XSSFSheet sheet = xwb.getSheetAt(0);
        int allsheetnumber=sheet.getLastRowNum();
        System.out.println(allsheetnumber);
        return allsheetnumber;
    }catch (Exception e){
        e.printStackTrace();
        try {

            HSSFWorkbook xwb1 = new HSSFWorkbook(new FileInputStream(filepath));  
            HSSFSheet sheet1= xwb1.getSheetAt(0);
            int allsheetnumber1=sheet1.getLastRowNum();
            return allsheetnumber1;
        }catch (Exception e1){
            e1.printStackTrace();
            return 0;
        }
    }    
}

 

PO类:CompletedQuantityPo

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.GenericGenerator;

import com.landicorp.core.BasePo;
import com.landicorp.core.FormColumn;

/**
 * 工程量总表和工程量复用逻辑
 * 
 * @author hopexx
 */

@Entity
@Table(name = "t_pilot_completed_quantity")
public class CompletedQuantityPo extends BasePo {
    
    private static final long serialVersionUID = 3296083232158423040L;
    
    /**  */
    @FormColumn(title = "", listShow = false, editShow = false)
    @Id
    @Column(name = "ID")
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;
    
    /** 交工ID或者工序ID */
    @FormColumn(title = "交工ID")
    @Column(name = "CR_ID")
    private String crId;
    
    /** 报告实体ID */
    @FormColumn(title = "报告实体ID")
    @Column(name = "REPORT_ID")
    private Integer reportId;
    
    /** 项目主键ID */
    @FormColumn(title = "项目主键ID")
    @Column(name = "PRO_ID")
    private String proId;
    
    /** 项目名称 */
    @FormColumn(title = "项目名称")
    @Column(name = "PRO_NAME")
    private String proName;
    
    /** 明目 */
    @FormColumn(title = "明目")
    @Column(name = "COM_NAME")
    private String comName;
    
    /** 单位 */
    @FormColumn(title = "单位")
    @Column(name = "UNIT")
    private String unit;
    
    /** 定额编号 */
    @FormColumn(title = "定额编号")
    @Column(name = "QUOTA_NUMBER")
    private String quotaNumber;
    
    /** 数量 */
    @FormColumn(title = "数量")
    @Column(name = "COM_NUM")
    private String comNum;
    
    /** 工日系数 */
    @FormColumn(title = "工日系数")
    @Column(name = "CONSUMPTION_COEFFICIENT")
    private String consumptionCoefficient;

    /** 单位技工 */
    @FormColumn(title = "单位技工")
    @Column(name = "UNIT_MECHANIC")
    private String unitMechanic;

    /** 单位普工 */
    @FormColumn(title = "单位普工")
    @Column(name = "UNIT_GENERAL_WORKER")
    private String unitGeneralWorker;
    
    /** 单位技工 */
    @FormColumn(title = "单位技工")
    @Column(name = "MECHANIC")
    private String mechanic;
    
    /** 单位普工 */
    @FormColumn(title = "单位普工")
    @Column(name = "GENERAL_WORKER")
    private String generalWorker;
    
    /** 施工单位ID */
    @FormColumn(title = "施工单位ID")
    @Column(name = "BUILD_ID")
    private Integer buildId;
    
    /** 施工单位名称 */
    @FormColumn(title = "施工单位名称")
    @Column(name = "BUILD_ORGANIZATION")
    private String buildOrganization;
    
    /** 状态 */
    @FormColumn(title = "状态")
    @Column(name = "STATUS")
    private Integer status;
    
    /** 量表类型 1为交工量总表\0为工序工程量表 */
    @FormColumn(title = "量表类型")
    @Column(name = "QUANTITY_TYPE")
    private Integer quantityType;
    
    /** 备注 */
    @FormColumn(title = "备注")
    @Column(name = "REMARK")
    private String remark;
    
    /** 附件 */
    @FormColumn(title = "附件")
    @Column(name = "FILE_PATH")
    private String filePath;
    
    /**  */
    @Column(name = "CREATOR_ID")
    private Integer creatorId;
    
    /** 创建人姓名 */
    @FormColumn(title = "创建人姓名")
    @Column(name = "CREATOR_NAME")
    private String creatorName;
    
    /**  */
    @Column(name = "CREATE_TIME")
    private java.sql.Timestamp createTime;
    
    /**  */
    @Column(name = "LAST_MODIFIER")
    private Integer lastModifier;
    
    /**  */
    @Column(name = "LAST_MODIFY_TIME")
    private java.sql.Timestamp lastModifyTime;

    /** 变更类型:0原始方案,变更:1,追加:2,停止:3 */
    @Column(name = "CHANGE_TYPE")
    private Integer changeType;
    
    
    /** 变更方案ID */
    @Column(name = "DCH_ID")
    private String dchId;
    
    
    /** 变更工序场景ID */
    @Column(name = "CH_GXID")
    private String chGxId;
    
    
    /** 方案无法执行的原因 */
    @Column(name = "CHANGE_REASON")
    private String chReason;
    
    
    /** 变更量 */
    @Column(name = "CHANGE_NUM")
    private Double chNum;
    
    
    /** 变更是否生效    0为不生效,Null为生效 */
    @Column(name = "IS_ENABLE_CH")
    private String isEnableCh;
    
    
    /** 变更版本 */
    @Column(name = "CHANGE_VERSION")
    private Integer changeVersion;
    
    
    /** 变更时间 */
    @FormColumn(title = "变更时间 ")
    @Column(name = "CHANGE_TIME")
    private java.sql.Timestamp changeTime;
    
    /** 变更人 ID*/
    @Column(name = "CHANGE_USER_ID")
    private Integer changeUserId;
    
    /** 施工日志查看工序对应工程量,1提交,2删除*/
    @Column(name = "log_or_state",insertable=false)
    private String  logOrState;
    
    /** 在施工日志中此工程量是否确认,1确认,2非确认*/
    @Column(name = "log_login")
    private Integer logLogin;
    
    @Transient
    private Integer one;
    
    @Transient
    private Integer gclcount;
    
    
    public Integer getOne() {
        return one;
    }


    
    public void setOne(Integer one) {
        this.one = one;
    }


    
    public Integer getGclcount() {
        return gclcount;
    }


    
    public void setGclcount(Integer gclcount) {
        this.gclcount = gclcount;
    }


    public String getLogOrState() {
        return logOrState;
    }

    
    public void setLogOrState(String logOrState) {
        this.logOrState = logOrState;
    }

    
    public Integer getLogLogin() {
        return logLogin;
    }

    
    public void setLogLogin(Integer logLogin) {
        this.logLogin = logLogin;
    }

    public Integer getBuildId() {
        return this.buildId;
    }
    
    public String getBuildOrganization() {
        return this.buildOrganization;
    }

    public String getComName() {
        return this.comName;
    }
    
    public String getComNum() {
        return this.comNum;
    }
    
    public String getConsumptionCoefficient() {
        return this.consumptionCoefficient;
    }
    
    public java.sql.Timestamp getCreateTime() {
        return this.createTime;
    }
    
    public Integer getCreatorId() {
        return this.creatorId;
    }
    
    public String getCreatorName() {
        return this.creatorName;
    }
    
    public String getCrId() {
        return this.crId;
    }
    
    public String getFilePath() {
        return this.filePath;
    }
    
    public String getGeneralWorker() {
        return this.generalWorker;
    }
    
    @Override
    public String getId() {
        return this.id;
    }
    
    public Integer getLastModifier() {
        return this.lastModifier;
    }
    
    public java.sql.Timestamp getLastModifyTime() {
        return this.lastModifyTime;
    }
    
    public String getMechanic() {
        return this.mechanic;
    }
    
    public String getProId() {
        return this.proId;
    }
    
    public String getProName() {
        return this.proName;
    }
    
    public Integer getQuantityType() {
        return this.quantityType;
    }
    
    public String getQuotaNumber() {
        return this.quotaNumber;
    }
    
    public String getRemark() {
        return this.remark;
    }
    
    public Integer getReportId() {
        return this.reportId;
    }
    
    public Integer getStatus() {
        return this.status;
    }
    
    public String getUnit() {
        return this.unit;
    }
    
    public String getUnitGeneralWorker() {
        return this.unitGeneralWorker;
    }
    
    public String getUnitMechanic() {
        return this.unitMechanic;
    }
    
    public void setBuildId(Integer buildId) {
        this.buildId = buildId;
    }
    
    public void setBuildOrganization(String buildOrganization) {
        this.buildOrganization = buildOrganization;
    }
    
    public void setComName(String comName) {
        this.comName = comName;
    }
    
    public void setComNum(String comNum) {
        this.comNum = comNum;
    }
    
    public void setConsumptionCoefficient(String consumptionCoefficient) {
        this.consumptionCoefficient = consumptionCoefficient;
    }
    
    public void setCreateTime(java.sql.Timestamp createTime) {
        this.createTime = createTime;
    }
    
    public void setCreatorId(Integer creatorId) {
        this.creatorId = creatorId;
    }
    
    public void setCreatorName(String creatorName) {
        this.creatorName = creatorName;
    }
    
    public void setCrId(String crId) {
        this.crId = crId;
    }
    
    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
    
    public void setGeneralWorker(String generalWorker) {
        this.generalWorker = generalWorker;
    }
    
    @Override
    public void setId(String id) {
        this.id = id;
    }
    
    public void setLastModifier(Integer lastModifier) {
        this.lastModifier = lastModifier;
    }
    
    public void setLastModifyTime(java.sql.Timestamp lastModifyTime) {
        this.lastModifyTime = lastModifyTime;
    }
    
    public void setMechanic(String mechanic) {
        this.mechanic = mechanic;
    }
    
    public void setProId(String proId) {
        this.proId = proId;
    }
    
    public void setProName(String proName) {
        this.proName = proName;
    }
    
    public void setQuantityType(Integer quantityType) {
        this.quantityType = quantityType;
    }
    
    public void setQuotaNumber(String quotaNumber) {
        this.quotaNumber = quotaNumber;
    }
    
    public void setRemark(String remark) {
        this.remark = remark;
    }
    
    public void setReportId(Integer reportId) {
        this.reportId = reportId;
    }
    
    public void setStatus(Integer status) {
        this.status = status;
    }
    
    public void setUnit(String unit) {
        this.unit = unit;
    }
    
    public void setUnitGeneralWorker(String unitGeneralWorker) {
        this.unitGeneralWorker = unitGeneralWorker;
    }
    
    public void setUnitMechanic(String unitMechanic) {
        this.unitMechanic = unitMechanic;
    }

    
    public Integer getChangeType() {
        return changeType;
    }

    
    public void setChangeType(Integer changeType) {
        this.changeType = changeType;
    }

    
    public String getDchId() {
        return dchId;
    }

    
    public void setDchId(String dchId) {
        this.dchId = dchId;
    }

    
    public String getChGxId() {
        return chGxId;
    }

    
    public void setChGxId(String chGxId) {
        this.chGxId = chGxId;
    }

    
    public String getChReason() {
        return chReason;
    }

    
    public void setChReason(String chReason) {
        this.chReason = chReason;
    }

    
    public Double getChNum() {
        return chNum;
    }

    
    public void setChNum(Double chNum) {
        this.chNum = chNum;
    }

    
    public String getIsEnableCh() {
        return isEnableCh;
    }

    
    public void setIsEnableCh(String isEnableCh) {
        this.isEnableCh = isEnableCh;
    }

    
    public Integer getChangeVersion() {
        return changeVersion;
    }

    
    public void setChangeVersion(Integer changeVersion) {
        this.changeVersion = changeVersion;
    }

    
    public java.sql.Timestamp getChangeTime() {
        return changeTime;
    }

    
    public void setChangeTime(java.sql.Timestamp changeTime) {
        this.changeTime = changeTime;
    }

    
    public Integer getChangeUserId() {
        return changeUserId;
    }

    
    public void setChangeUserId(Integer changeUserId) {
        this.changeUserId = changeUserId;
    }
}

类:ZuobiaoInfo

public class ZuobiaoInfo {
    
    public String Method;//方法名
    public String name;
    public int zongzuobiao;//纵坐标

    
     public ZuobiaoInfo(){
        
    }
     public ZuobiaoInfo(String Method, String name ,int zongzuobiao){
         this.Method=Method;
         this .zongzuobiao=zongzuobiao;
         this .name=name;
     }
    public int getZongzuobiao() {
        return zongzuobiao;
    }
    public void setZongzuobiao(int zongzuobiao) {
        this.zongzuobiao = zongzuobiao;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    public String getMethod() {
        return Method;
    }
    
    public void setMethod(String method) {
        Method = method;
    }
     
     
     
}
posted @ 2018-11-28 16:59  G-&-D  阅读(1348)  评论(0编辑  收藏  举报