POI导入

1.基本功能 1.基本功能

导入功能使用的是是EC的POI导入功能,导入需要配置对应的模板文件。对应的excel模板平台默认生成的路径是WebContent路径。但是在实际使用中需要对excel模板文件进行调整。
– POI模板读取策略,从Tomcat目录中读取,一般是开发期使用或者是单系统引用。
glpaas.poi.readTemplteStrategy=default
– POI模板读取策略,从Jar中读取,一般是SpringBoot项目使用。如果是jar需要确保对应的excel文件可以打包到jar中,可以手工拷贝到resource下或者是通过pom文件配置打包时自动拷贝到jar中。
glpaas.poi.readTemplteStrategy=jar
– POI模板读取策略,从Ftp中读取,单系统、SpringBoot项目都可以使用。
glpaas.poi.readTemplteStrategy=ftp

1.1. 单表导入Excel 1.1.单表导入Excel

平台支持配置单表导入Excel数据,也支持主子表下配置子表导入Excel。

1.2. 主从表导入Excel 1.2. 主从表导入Excel

平台支持配置主从表导入Excel数据。

1.3. 新导入Excel 1.3. 新导入Excel

新导入采用的是异步导入,导入的时候可以对字段配置非空校验。校验不通过的时候,可以下载错误日志,查看错误。
10

1.4. 自定义导入Excel 1.4. 自定义导入Excel

导入模板有复杂的表头,未采用云平台的POI配置,通过自定义导入代码实现功能。
QQ图片20180913133514

1.5. 下载模板1.5. 下载模板

平台支持配置下载模板功能,例如下载导入Excel模板。
下载模板-效果1

2. 配置方法 2. 配置方法

2.1. 2.1. 单表导入Excel 单表导入Excel

  • 如果业务对象中有勾选【生成导入模板】复选框,那么平台会自动生成对应的POI数据,不需要用户再配置。
  • 子表导入的配置一样,但是子表导入前提是主业务对象必须先保存,即有对应的主键。
  • 配置

    1. 对象建模–业务对象–业务对象管理:编辑业务对象,点击【可视化布局】按钮,进入到可视化界面。
    2. 选中TOOLBAR后点击右上方齿轮按钮,将导入Excel方法配置到界面上。
      QQ截图20191028153654
    3. 编辑业务对象,在右侧业务对象选项中找到【生成导入模板】复选框并打钩,然后保存数据。
      QQ截图20191028152344
    4. 提交业务对象,点击【选择生成】代码按钮,在生成的代码文件中会有默认的导入模板,模板路径在/目标工程名/WebContent/uploadFiles/local/下,文件名为业务对象名+Import.xlsx。如果需要调整模板,可以根据路径找到模板编辑修改即可。
      QQ截图20191028152510
      QQ截图20191028154138

    代码

    前端html文件会生成导入按钮。

    <g-import-excel     key="TestExam3101Ghx" show-waiting-dialog="true" g-per="/testExam3101Ghx/importTestExam3101GhxData"  callback="importCallbackTestExam3101Ghx(response)" import_url="{{$config.ctx}}/import/excel" display-express="导入Excel" css-class="button-primary-div"   ></g-import-excel>
    

    后端实现类会生成导入方法:importExcel

     public String importExcel(List<com.gillion.ttt.test.domain.TestExam3101Ghx> dataList, Map<String, Object> paramMap)
                throws Exception {
            try {
                Map<String, Object> dataMap = new HashMap<String, Object>();
                dataMap.put("dataList", dataList);
                dataMap.put("paramMap", paramMap);
                RuleService ruleService = SpringContextHolder.getBeanByType(RuleService.class);
                if (dataList.size() > 0) {
                    //批量插入数据
                    this.batchInsert(dataList);
                    Map<String, Object> result = Maps.newHashMap();
                    result.put("msg", "导入成功");
                    result.put("callBack", "getTestExam3101GhxPages()");
                    dataMap.put(RESULT, result);
                } else {
                    Map<String, Object> result = Maps.newHashMap();
                    result.put("msg", "导入数据为空,请确认");
                    dataMap.put(RESULT, result);
                }
                Map<String, Object> result = Maps.newHashMap();
                result.put(RESULT, dataMap.get(RESULT));
                result.put("success", true);
                return JSONObject.fromObject(result).toString();
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception(e.getCause().getMessage());
            }
        }
    

    2.2. 主从表导入Excel 2.2. 主从表导入Excel

    如果是分布式项目且是集群部署的,每个tomcat对应目录下都要把模板放上去,不然会出现取不到模板的情况。

    配置

    1. 根据需求制作导入模板,把主表字段放在子表字段的前面。
      QQ截图20191030110924
    2. 对象建模–基础数据–POI配置管理:新增一个主从表导入POI配置,POI配置完要把数据刷到对应的业务系统数据库
      QQ截图20191030112016
      1)模板路径为【/uploadFiles/local/模板文件名】,例如【/uploadFiles/local/TestExam3101Template.xlsx】
      2)POI对象全名:业务对象的包路径,例如com.gillion.sample.test.domain.TestExam3201
      3)主键指定:业务对象的主键,例如{“primaryTable”:”asnNo”}
      4)子表信息定义类:{“testExam3201Details”:”com.gillion.sample.test. domain.TestExam3201Detail”}
      5)导入字段定义:{“primaryTable”:”asnNo,custNo,receiptType”,”testExam3201Details”:”itemName,planQty,receiveQty,openQty”}
    3. 编辑业务对象–业务对象扩展,新增一个扩展类,该步骤可参考 扩展主从表导入扩展类的代码可参考常用扩展
      QQ截图20191030112510
    4. 编辑业务对象–方法定义下的导入Excel方法,新增一笔规则,该步骤可参考 扩展
      QQ截图20191030135307
    5. 点击【可视化布局】按钮,进入布局,将导入Excel按钮配置到界面上。
      QQ截图20191030135901

    代码

    前端html文件会生成导入按钮。

     <g-import-excel     key="TestExam3201" show-waiting-dialog="true" g-per="/testExam3201/importTestExam3201Data"  callback="importCallbackTestExam3201(response)" import_url="{{$config.ctx}}/import/excel" display-express="导入Excel" css-class="button-primary-div"   ></g-import-excel>
    

    后端实现类会生成导入方法:importExcel,且方法中会生成调用规则的代码testExam3201ImportService.find(dataMap);

    public String importExcel(List<com.gillion.sample.test.domain.TestExam3201> dataList, Map<String, Object> paramMap)
                throws Exception {
            try {
                Map<String, Object> dataMap = new HashMap<String, Object>();
                dataMap.put("dataList", dataList);
                dataMap.put("paramMap", paramMap);
                RuleService ruleService = SpringContextHolder.getBeanByType(RuleService.class);
                testExam3201ImportService.find(dataMap);
                Map<String, Object> result = Maps.newHashMap();
                result.put(RESULT, dataMap.get(RESULT));
                result.put("success", true);
                return JSONObject.fromObject(result).toString();
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception(e.getCause().getMessage());
            }
        }
    

    2.3. 2.3. 新导入Excel 新导入Excel

  • 目前只支持单系统,分布式暂不支持。
  • 支持版本:5.3.0.0版本以上。
  • 如果是spring-boot项目需在配置文件yml开启配置:poi:enabled:true

  • QQ截图20191030153807

    配置

    1. 对象建模–业务对象–业务对象管理:编辑业务对象–方法定义,点击新增按钮,输入【调用方法名称】为newImport、【调用方法描述】、【方法类型】选择新导入、【URL地址】为业务对象名(首字母小写)/方法名,【文件路径】如果不填默认为以resources为根路径,如果用户自己想定义配置文件可以自己加,文件命名规则为config.当前业务对象_zh_CN.properties,真实文件需加入到工程代码中。
      QQ截图20191030160739
      5
    2. 配置扩展方法:目前平台只做到把导入的数据转成实体对象,再回传方法由项目组扩展,进一步校验和保存操作。需扩展服务类进行保存操作。项目组自行校验所有内容都可以从ExcelImportConfig中取得,如果有校验出错,可以从对象excelImportConfig中的对象属性取的对象加入错误列表
      6
      ExcelImportConfig对象:
      7
      下面方法供项目组使用把收集的错误加到列表中
      8
    3. 编辑业务对象,进入可视化布局界面,将新导入Excel方法配置到界面上。
      QQ截图20191030164308
    4. 提交业务对象,生成代码。

    代码

    config.当前业务对象_zh_CN.properties文件写法参考如下:

    validRequire=名称,新增单号,金额
    property={"物理主键":"testLixq101Id","名称":"testCaseName","新增单号":"testCaseNameTwo","复选框":"yesOrNo","金额":"testCaseValue","字符日期":"testCharDate","字符日期时间":"testCharDatetime","测试时间":"testDate","日期时间型测试":"testDatetime"}
    validRequire:用来配置导入的那些列不能为空校验
    property:填入列名和列名对应的属性名(业务对象的属性),需导入的列最好全部列出来,要不会提示找不到列名校验
    

    11

    2.4. 自定义导入Excel2.4. 自定义导入Excel

    配置

    1. 对象建模–业务对象–业务对象管理:编辑业务对象–方法定义,新增一个自定义JS导入方法,并将这个方法配置到界面上。该步骤可参考可参考 自定义JS
    2. 扩展实现的代码可以参考常用扩展3.2. 自定义导入Excel

    2.5. 下载模板2.5. 下载模板

    配置

    1. 对象建模–业务对象–业务对象管理:编辑业务对象–方法定义,在方法定义中新增一个按钮:【调用方法名称】为uploadFile,【调用方法描述】,【方法类型】为自定义下载,【调用url地址】为业务对象(首字母小写)/调用方法名称,【文件地址】可自定义,但是放在WebContent下面,也可参照例子的路径:/uploadFiles/local/TestLixq301Template.xlsx。
      下载模板-配置1
    2. 点击进去可视化布局,将新增的方法配置到界面上。
      下载模板-配置2
    3. 打开工程目录,在方法定义的【文件路径】中放入需要下载的文件。
      下载模板-配置3
    4. 提交对象,生成代码。前端代码即可。

    代码

    Html中对应的下载按钮。

    <button g-pause-click ext-property="1" id="testLixq301Db.uploadFileTestLixq301Db" type="button" ng-click="uploadFileTestLixq301Db()" g-per="/testLixq301Db/uploadFile" ng-cloak class="button-primary" > 文件下载 </button>
    

    在js文件中对应的js代码.

    $scope.uploadFileTestLixq301Db = function(){
            var temp = "";
                var param = {};
                param.businessType = "First";
                window.location.href=$config.ctx + "/uploadFiles/local/TestLixq301DbTemplate.xlsx";
            };
    

    3. 常用扩展 3. 常用扩展

    3.2. 主从表导入Excel 3.2. 主从表导入Excel

    主从表导入扩展类的代码参考如下:

    package com.gillion.sample.test.custom;
    import java.util.*;
    import java.math.BigDecimal;
    import com.gfa4j.util.StringUtils;
    import com.gillion.platform.framework.component.dictionary.domain.DictionaryRows;
    import com.gillion.platform.framework.component.dictionary.service.DictionaryServiceExt;
    import com.gillion.platform.framework.core.BusinessException;
    import com.google.common.collect.Maps;
    import net.sf.json.JSONObject;
    import net.sf.json.JSONArray;
    import com.gillion.platform.framework.core.service.BaseServiceImplExt;
    import com.gillion.platform.utils.SpringContextHolder;
    import com.gillion.sample.test.domain.TestExam3201;
    import com.gillion.sample.test.service.TestExam3201Service;
    import com.gillion.sample.test.domain.TestExam3201Detail;
    import com.gillion.sample.test.service.TestExam3201DetailService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    @Service
    @SuppressWarnings("all")
    public class TestExam3201ImportService extends BaseServiceImplExt {
    @Autowired
    private DictionaryServiceExt dictionaryServiceExt;
    
    public void find(Map dataMap) {
    System.out.println("开始调用规则:TestExam201ImportExcel");
    List data = (List) dataMap.get("dataList");
    Map paramMap = (Map) dataMap.get("paramMap");
    
    Map result = new HashMap();
    try {
    TestExam3201Service testExam3201Service = (TestExam3201Service) SpringContextHolder.getBean(TestExam3201Service.class);
    TestExam3201DetailService testExam3201DetailService = (TestExam3201DetailService) SpringContextHolder.getBean(TestExam3201DetailService.class);
    //TODO 查询字典表
    Map<String, List> dictRowMaps = dictionaryServiceExt.queryDictRows("ReceiptType", null, false, false);
    Map<String, Map<String, String>> dictRowMap = Maps.newHashMap();
    if(null!=dictRowMaps){
    for(String dictCode : dictRowMaps.keySet()) {
    Map<String, String> dictRow = Maps.newHashMap();
    List dictRowList = dictRowMaps.get(dictCode);
    for (DictionaryRows row : dictRowList) {
    dictRow.put(row.getName(), row.getCode());
    }
    dictRowMap.put(dictCode,dictRow);
    }
    }
    for (int i = 0; i < data.size(); i++) {
    TestExam3201 testExam3201 = (TestExam3201) data.get(i);
    //TODO 校验数据 非空校验
    //校验数据,客户订单号必填
    if (testExam3201.getCustNo() == null || "".equals(testExam3201.getCustNo().trim())) {
    throw new Exception("客户订单号不能为空");
    }
    //TODO 校验数据 字典表值合法性校验
    String receiptType = testExam3201.getReceiptType();
    if (StringUtils.isNotBlank(receiptType)) {
    if(dictRowMap.containsKey("ReceiptType")){
    Map<String,String> dictMap = dictRowMap.get("ReceiptType");
    if(null!=dictMap && !dictMap.containsKey(receiptType)){
    throw new BusinessException("值["+receiptType+"]非法,没在字典表值范围内。");
    }
    }
    }
    testExam3201.setRowStatus(4);
    testExam3201Service.save(testExam3201);
    //导入子表
    String testExam3201Id = testExam3201.getTestExam3201Id();
    Set testExam3201Details = testExam3201.getTestExam3201Details();
    Iterator it = testExam3201Details.iterator();
    
    int detailIndex = 0;
    //导入相应明细
    while (it.hasNext()) {
    TestExam3201Detail testExam3201Detail = it.next();
    System.out.println(JSONObject.fromObject(testExam3201Detail));
    testExam3201Detail.setTestExam3201Id(testExam3201Id);
    System.out.println("开始保存第" + (detailIndex + 1) + "条ASN单的明细");
    testExam3201Detail.setRowStatus(4);
    testExam3201DetailService.save(testExam3201Detail);
    System.out.println("成功保存了第" + i + "条ASN的" + (detailIndex + 1) + "条明细");
    detailIndex++;
    }
    }
    result.put("msg", "导入成功");
    } catch (Exception e) {
    result.put("msg", e.getMessage());
    }
    dataMap.put("result", result);
    }
    };
    

    3.4. 自定义导入Excel 3.4. 自定义导入Excel

    控制器代码

    package org.activiti.image.impl;
    
    import com.gillion.platform.ecm.domain.EcmRepairEstmate;
    import com.gillion.platform.ecm.domain.EcmRepairEstmateExample;
    import com.gillion.platform.framework.core.service.IBaseService;
    import com.gillion.platform.framework.core.web.BaseAbstractController;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.commons.CommonsMultipartFile;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Map;
    
    @SuppressWarnings("all")
    @Controller
    public class EcmRepairEstmateControllerExt extends BaseAbstractController {
    
    EcmRepairEstmateServiceExt ecmRepairEstmateServiceExt;
    
    @RequestMapping(value = "/test/import")
    public void imortData(@RequestParam(value = "fileNae") MultipartFile[] files, String testId) throws IOException {
    CommonsMultipartFile file = (CommonsMultipartFile)files[0];
    
    ecmRepairEstmateServiceExt.importExcel(file);
    /*
    主要的过程 MultipartFile对象,取得文件流对象,excel工作簿对象接收流对象组装HSSFWorkbook对象
    
    InputStream inputStream = file.getInputStream();
    //流转换为工作簿对象
    HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
    HSSFSheet sheet = workbook.getSheetAt(0);//取得工作簿
    HSSFRow row = sheet.getRow(0);//行
    
    */
    
    }
    
    @Override
    public String getBoName() {
    return null;
    }
    }
    

    实现类代码

    package com.gillion.platform.ecm.service;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.math.BigDecimal;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.UUID;
    
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFDataFormat;
    import org.apache.poi.hssf.usermodel.HSSFDateUtil;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.commons.CommonsMultipartFile;
    
    import com.gfa4j.util.StringUtils;
    import com.gfa4j.utils.UserUtils;
    import com.gillion.platform.ecm.domain.EcmRepairEstmate;
    import com.gillion.platform.ecm.domain.EcmRepairEstmateExample;
    import com.gillion.platform.ecm.domain.EcmRepiarEstmateDetal;
    import com.gillion.platform.framework.core.domain.BaseObject;
    import com.gillion.platform.framework.core.query.Operation;
    import com.gillion.platform.framework.core.service.BaseServiceImplExt;
    import com.gillion.platform.sms.domain.SysDownloadd;
    import com.gillion.platform.sms.service.SysDownloaddService;
    import com.gillion.platform.sys.permission.domain.SysUser;
    import com.gillion.platform.sys.permission.service.SysUserService;
    import com.google.common.collect.Lists;
    @Service
    @SuppressWarnings("all")
    public class EcmRepairEstmateServiceImplExt extends
    BaseServiceImplExt<String, EcmRepairEstmate, EcmRepairEstmateExample>
    implements EcmRepairEstmateServiceExt {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysDownloaddService sysDownloaddService;
    
    @Autowired
    EcmRepairBillService billService;
    @Autowired
    EcmRepairEstmateService ecmRepairEstmateService;
    
    @Autowired
    EcmRepiarEstmateFileService fileService;
    @Autowired
    EcmRepiarEstmateDetalService detalService;
    String nowtime;
    SysUser sysUser;
    String offceCode;
    String errorInfo1;
    StringBuffer errorInfo2;// 错误信息汇总
    InputStream is = null;
    /**
    * 导入估价单
    */
    @Override
    public Map<String, String> importExcel(CommonsMultipartFile file) {
    Map<String, String> rsmap=new HashMap<String, String>();//返回值的集合
    try {
    EcmRepairEstmate newEcmRepairEstmate = verifyExcel(file,null);//解析文件 因为不是重新导入,所以第二个传null
    if(StringUtils.isEmpty(errorInfo1)&&StringUtils.isEmpty(errorInfo2)){
    
    //如果解析没错,就开始存数据库
    saveImportEcmRepairEstmate(newEcmRepairEstmate);
    //开始存详表
    int last= saveImportDetil(newEcmRepairEstmate,newEcmRepairEstmate.getEcmRepiarEstmateDetals());
    //存完记得文件也用输出流保存
    writeImportEcmRepairEstmate(newEcmRepairEstmate.getEcmRepairEstmateId(),file);
    System.err.println("===================导入完毕======================");
    }else{
    rsmap.put("errorInfo1", errorInfo1);
    rsmap.put("errorInfo2", errorInfo2.toString());
    }
    
    } catch (NullPointerException e) {
    e.printStackTrace();
    rsmap.put("errorExcel", "请根据模板文件导入!");
    } catch (Exception e) {
    e.printStackTrace();
    rsmap.put("errorExcel", "导入异常!");
    }finally {
    if (is != null) {
    try {
    is.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    return rsmap;
    }
    
    /**
    * 校验Excel的公共方法
    * @param file
    * @param jdbcTemplate
    * @return
    * @throws IOException
    */
    private EcmRepairEstmate verifyExcel(CommonsMultipartFile file,EcmRepairEstmate old) throws Exception {
    errorInfo2=new StringBuffer("");
    errorInfo1="";
    JdbcTemplate jdbcTemplate=this.getJdbcTemplate();
    EcmRepairEstmate newEcmRepairEstmate = new EcmRepairEstmate();
    String userId=(String)UserUtils.getCurrentLoginUser().getUserId();
    sysUser=sysUserService.loadById(userId);
    
    
    is = file.getInputStream();
    String fileName = file.getOriginalFilename();
    
    Workbook workbook = null;
    if (isExcel2003(fileName)) {
    workbook = new HSSFWorkbook(is);
    } else {
    workbook = new XSSFWorkbook(is);
    }
    Sheet sheet = workbook.getSheetAt(0);
    
    Row row;
    int s = sheet.getPhysicalNumberOfRows();// 总行数
    String tankno = getCellAsString(sheet.getRow(1).getCell(7)).toUpperCase().trim();// 箱号
    String repairDepotCode = getCellAsString(sheet.getRow(3).getCell(0)).toUpperCase().trim();// 修箱堆场码
    String repairDepot="";//修箱堆场 根据堆场码去供应商表查
    String gateInDate = getCellAsString(sheet.getRow(4).getCell(7)).trim();// 进场日期
    String productName = getCellAsString(sheet.getRow(5).getCell(3)).toUpperCase().trim();// 品名
    String skNo = getCellAsString(sheet.getRow(10).getCell(11)).toUpperCase().trim();// 托单编号
    String moveNo = getCellAsString(sheet.getRow(11).getCell(11)).toUpperCase().trim();// MOVE编号
    
    
    BigDecimal labourRate=new BigDecimal(0); // 工时费率,要根据修箱堆场从数据字典里面取
    BigDecimal sumtotal = new BigDecimal(0); // 修箱金额,是要算出来的
    if (StringUtils.isEmpty(tankno)) {
    errorInfo2.append("第2行第8列箱号不能为空!<br>");
    }
    if (StringUtils.isEmpty(repairDepotCode)) {
    errorInfo2.append("第4行第1列修箱堆场代码不能为空!<br>");
    }
    if (StringUtils.isEmpty(gateInDate)) {
    errorInfo2.append("第5行第8列进场日期不能为空!<br>");
    }
    if (StringUtils.isEmpty(productName)) {
    errorInfo2.append("第6行第4列品名不能为空!<br>");
    }
    List<String> list;
    //select c.supplier_name_cn,category from CSP_SUPPILER c where c.supplier_code='TJBHDEP'
    StringBuffer stbufrepairDepot = new StringBuffer();
    stbufrepairDepot.append("select c.supplier_name_cn,c.category,c.status from CSP_SUPPILER c where c.supplier_code='"+repairDepotCode+"'");
    //repairDepot=jdbcTemplate.queryForObject(stbufrepairDepot.toString(),String.class);
    List rowlist=jdbcTemplate.queryForList(stbufrepairDepot.toString());
    Iterator it=rowlist.iterator();
    if(it.hasNext()) {
    Map result=(Map)it.next();
    if(!"Y".equals(result.get("CATEGORY"))){
    errorInfo2.append("第4行第1列不是堆场代码!<br>");
    }else if(!"P".equals(result.get("STATUS"))){
    errorInfo2.append("该堆场不是财务审核状态!<br>");
    }else {
    repairDepot=result.get("SUPPLIER_NAME_CN").toString();
    }
    
    }else{
    errorInfo2.append("修箱堆场代码不存在!<br>");
    }
    
    
    if(!isValidDate(gateInDate)){
    errorInfo2.append("进场日期不合法!<br>");
    }
    
    StringBuffer stbuftankno = new StringBuffer();
    stbuftankno.append("select e.tank_no from ECM_TANK_BASEINFO e where e.tank_no='"+tankno+"'");
    list=jdbcTemplate.queryForList(stbuftankno.toString(),String.class);
    if(list.size()!=1){
    errorInfo2.append("箱号不存在!<br>");
    }
    
    StringBuffer stbuflabourRate = new StringBuffer();
    stbuflabourRate.append("select c.Dict_Code from CDM_DICT_BASE b,CDM_DICT_CODE c where ");
    stbuflabourRate.append(" b.Cdm_Dict_Base_Id=c.cdm_dict_base_id and b.dict_type='ECM_REPAIR_LABOUR' and DICT_CODE_CN='"+repairDepotCode+"'");
    //labourRate=new BigDecimal(jdbcTemplate.queryForObject(stbuflabourRate.toString(),String.class));
    list=jdbcTemplate.queryForList(stbuflabourRate.toString(),String.class);
    if(list.size()!=1){
    errorInfo2.append("修箱堆场代码未维护对应的工时费率!<br>");
    }else{
    labourRate=new BigDecimal(list.get(0));
    }
    
    
    if (old != null) { //重新导入
    if (!(tankno.equals(old.getTankNo())
    && repairDepotCode.equals(old.getRepairDepotCode()) && dateChange(
    gateInDate).equals(old.getGateInDate()))) {
    errorInfo1 = "修箱公司、箱号、进场时间与原估价单不一致,请检查后重新导入!";
    }
    } else { //导入
    StringBuffer countSql2 = new StringBuffer();
    countSql2
    .append("select count(*) from ECM_REPAIR_ESTMATE e where ");
    countSql2.append("e.tank_no='" + tankno
    + "' and e.repair_depot_code='" + repairDepotCode
    + "' and e.gate_in_date='" + dateChange(gateInDate) + "'");
    int reapirNum = jdbcTemplate.queryForObject(countSql2.toString(),
    Integer.class);
    if (reapirNum > 0) {
    errorInfo1 = "该估价单已经存在,请到编辑界面重新导入";
    }
    }
    if (StringUtils.isEmpty(errorInfo1)){//估价单不存在则开始解析字表
    if(StringUtils.isEmpty(errorInfo2)){
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    nowtime=dateChange(formatter.format(new Date()));
    newEcmRepairEstmate.setEcmRepairEstmateId(UUID.randomUUID().toString());
    newEcmRepairEstmate.setTankNo(tankno);
    newEcmRepairEstmate.setRepairDepotCode(repairDepotCode);
    newEcmRepairEstmate.setRepairDepot(repairDepot);
    newEcmRepairEstmate.setGateInDate(dateChange(gateInDate));
    newEcmRepairEstmate.setProductName(productName);
    newEcmRepairEstmate.setSkNo(skNo);
    newEcmRepairEstmate.setMoveNo(moveNo);
    newEcmRepairEstmate.setLabourRate(labourRate);
    newEcmRepairEstmate.setRepairEstmateNo(repairDepotCode+tankno+dateChange(gateInDate));
    newEcmRepairEstmate.setVersion(new BigDecimal(1));
    newEcmRepairEstmate.setStatus("OPEN");
    newEcmRepairEstmate.setFeeStatus("PENDING");
    newEcmRepairEstmate.setNewFlag("Y");
    newEcmRepairEstmate.setLastModifyTime(nowtime);
    newEcmRepairEstmate.setCreateTime(nowtime);
    if(old!=null){
    BigDecimal newVersion=new BigDecimal(-1);//新版本号
    //根据估价单号从数据库查最大的版本号
    newVersion=jdbcTemplate.queryForObject("select max(e.version) from ecm_repair_estmate e where e.repair_estmate_no='"+old.getRepairEstmateNo()+"'", BigDecimal.class);
    if (newVersion==null) {
    newEcmRepairEstmate.setVersion(old.getVersion().add(new BigDecimal(1)));
    }else{
    newEcmRepairEstmate.setVersion(newVersion.add(new BigDecimal(1))); //版本号+1
    }
    
    }else {
    newEcmRepairEstmate.setVersion(new BigDecimal(1));
    }
    
    
    if(sysUser!=null){
    String offceCodeSql="select o.office_code from sys_user u ,sys_office o where u.sys_office_id=o.sys_office_id and u.sys_user_id='"+sysUser.getSysUserId()+"'";
    
    list= jdbcTemplate.queryForList(offceCodeSql, String.class);
    if(list.size()!=1){
    System.out.println("未获取到该用户的组织机构");
    }else {
    offceCode=list.get(0);
    }
    newEcmRepairEstmate.setRepairMan(sysUser.getUserNameCn());
    newEcmRepairEstmate.setRepairManCode(sysUser.getUserName());
    newEcmRepairEstmate.setCreator(sysUser.getUserName());
    newEcmRepairEstmate.setCreateOffice(offceCode);
    newEcmRepairEstmate.setCreateTimeZone(sysUser.getCreateTimeZone());
    newEcmRepairEstmate.setPrincipalGroupCode(sysUser.getPrincipalGroupCode());
    newEcmRepairEstmate.setLastModifyor(sysUser.getUserName());//最后修改人
    newEcmRepairEstmate.setLastModifyOffice(offceCode);
    }
    //品名代码
    //操作人 必输
    //操作人代码 必输
    //修箱完成时间
    
    }
    
    
    Set<EcmRepiarEstmateDetal> ecmRepiarEstmateDetals = new HashSet<EcmRepiarEstmateDetal>();
    int iDetal = 21;// 从第22行开始循环遍历详表
    // String aaString=
    // getCellAsString(sheet.getRow(71).getCell(7));//HOURS TOTAL
    while (!"HOURS TOTAL".equals(getCellAsString(sheet.getRow(
    iDetal).getCell(7)))) {
    String repairCompName = getCellAsString(sheet.getRow(iDetal).getCell(0)).toUpperCase().trim();// 部位名称
    String repairCompCode = "";//部位名称编码
    String repairItemName = getCellAsString(sheet.getRow(iDetal).getCell(1)).toUpperCase().trim();// 部位项目名称
    String repairItemCode="";//项目编码
    String repairDamageCode = getCellAsString(sheet.getRow(iDetal).getCell(2)).toUpperCase().trim();// 损坏代码
    String repairDamageName="";//损坏名称
    String repairCode = getCellAsString(sheet.getRow(iDetal).getCell(3)).toUpperCase().trim();// 修理代码
    String repairCodeName="";//修理名称
    String remark="";// 备注
    String hours="";// 工时
    String materialCost="";// 材料费
    BigDecimal subtotal;// 小计 工时*工时费率+材料费
    BigDecimal hoursCost;
    
    if (StringUtils.isEmpty(repairCompName)) {
    errorInfo2.append("第" + (iDetal + 1) + "行COMP不能为空!<br>");
    }
    if (StringUtils.isEmpty(repairItemName)) {
    errorInfo2.append("第" + (iDetal + 1) + "行ITEM不能为空!<br>");
    }
    
    if (StringUtils.isEmpty(repairDamageCode)
    && StringUtils.isEmpty(repairCode)) {
    iDetal++;// 没有这一项,下一行
    continue;
    } else if (StringUtils.isEmpty(repairDamageCode)) {
    errorInfo2.append("第" + (iDetal + 1) + "行DAMAGECODE不能为空!<br>");
    iDetal++;
    continue;
    } else if (StringUtils.isEmpty(repairCode)) {
    errorInfo2.append("第" + (iDetal + 1) + "行REPAIRCODE不能为空!<br>");
    iDetal++;
    continue;
    } else {
    remark = getCellAsString(sheet.getRow(iDetal).getCell(4));
    hours = getCellAsString(sheet.getRow(iDetal).getCell(9)).trim();
    materialCost = getCellAsString(sheet.getRow(iDetal).getCell(10)).trim();
    if(hours.length()<1){
    hours="0";
    }
    if(materialCost.length()<1){
    materialCost="0";
    }
    }
    //看字表对应的数据存不存在
    //做子表前4个的校验
    
    
    StringBuffer stbufrepairCompCode = new StringBuffer();
    stbufrepairCompCode.append("select e.repair_comp_code from ECM_REPAIR_COMP e where e.repair_comp_name='"+repairCompName+"'");
    list=jdbcTemplate.queryForList(stbufrepairCompCode.toString(),String.class);
    if(list.size()!=1){
    errorInfo2.append("第" + (iDetal + 1) + "行COMP不存在!<br>");
    }else {
    repairCompCode=list.get(0);
    }
    
    /*repairCompCode=jdbcTemplate.queryForObject(stbufrepairCompCode.toString(),String.class);
    if((StringUtils.isEmpty(repairCompCode))){
    errorInfo2 += "第" + (iDetal + 1) + "行COMP不存在" + "\!<br>";
    }*/
    
    StringBuffer stbufrepairItemCode = new StringBuffer();
    stbufrepairItemCode.append("select i.repair_item_code from ECM_REPAIR_COMP_ITEM i,ecm_repair_comp c where i.ecm_repair_comp_id=c.ecm_repair_comp_id");
    stbufrepairItemCode.append(" and i.repair_item_name='"+repairItemName+"' and c.repair_comp_name='"+repairCompName+"'");
    list=jdbcTemplate.queryForList(stbufrepairItemCode.toString(),String.class);
    if(list.size()!=1){
    errorInfo2.append("第" + (iDetal + 1) + "行"+repairCompName+"对应的ITEM不存在!<br>");
    }else {
    repairItemCode=list.get(0);
    }
    
    /*repairItemCode=jdbcTemplate.queryForObject(stbufrepairItemCode.toString(),String.class);
    if((StringUtils.isEmpty(repairItemCode))){
    errorInfo2 += "第" + (iDetal + 1) + "行ITEM不存在" + "\!<br>";
    }*/
    
    StringBuffer stbufrepairDamageName = new StringBuffer();
    stbufrepairDamageName.append("select e.repair_damage_name from ECM_REPAIR_DAMAGE e where e.repair_damage_code='"+repairDamageCode+"'");
    list=jdbcTemplate.queryForList(stbufrepairDamageName.toString(),String.class);
    if(list.size()!=1){
    errorInfo2.append("第" + (iDetal + 1) + "行DAMAGE CODE不存在!<br>");
    }else {
    repairDamageName=list.get(0);
    }
    /*repairDamageName=jdbcTemplate.queryForObject(stbufrepairDamageName.toString(),String.class);
    if((StringUtils.isEmpty(repairDamageName))){
    errorInfo2 += "第" + (iDetal + 1) + "行DAMAGE CODE不存在" + "\!<br>";
    }*/
    
    StringBuffer stbufrepairCodeName = new StringBuffer();
    stbufrepairCodeName.append("select e.repair_code_name from ECM_REPAIR_CODE e where e.repair_code='"+repairCode+"'");
    list=jdbcTemplate.queryForList(stbufrepairCodeName.toString(),String.class);
    if(list.size()!=1){
    errorInfo2.append("第" + (iDetal + 1) + "行REPAIR CODE不存在!<br>");
    }else {
    repairCodeName=list.get(0);
    }
    /*repairCodeName=jdbcTemplate.queryForObject(stbufrepairCodeName.toString(),String.class);
    if((StringUtils.isEmpty(repairCodeName))){
    errorInfo2 += "第" + (iDetal + 1) + "行REPAIR CODE不存在" + "\!<br>";
    }*/
    
    if(!hours.matches("-?[0-9]+.*[0-9]*")&&"".equals(hours)){
    errorInfo2.append("第" + (iDetal + 1) + "行HOURS不是数字!<br>");
    }
    if(!materialCost.matches("-?[0-9]+.*[0-9]*")&&"".equals(materialCost)){
    errorInfo2.append("第" + (iDetal + 1) + "行MATERIALCOST不是数字!<br>");
    }
    
    
    if(StringUtils.isEmpty(errorInfo1)&&StringUtils.isEmpty(errorInfo2)){
    EcmRepiarEstmateDetal detal = new EcmRepiarEstmateDetal();
    detal.setEcmRepairEstmateDetailId(UUID.randomUUID().toString());
    detal.setEcmRepairEstmateId(newEcmRepairEstmate.getEcmRepairEstmateId());//关联主表
    detal.setRepairCompCode(repairCompCode);
    detal.setRepairCompName(repairCompName);
    detal.setRepairItemCode(repairItemCode);
    detal.setRepairItemName(repairItemName);
    detal.setRepairCodeName(repairCodeName);
    detal.setLastModifyOffice(offceCode);
    detal.setCreateOffice(offceCode);
    detal.setRepairCode(repairCode);
    detal.setRepairDamageCode(repairDamageCode);
    detal.setRepairDamageName(repairDamageName);
    detal.setRemark(remark);
    detal.setStatus("Y");
    detal.setCreator(sysUser.getUserName());
    detal.setLastModifyor(sysUser.getUserName());
    detal.setHours(new BigDecimal(hours));
    detal.setMaterialCost(new BigDecimal(materialCost));
    hoursCost=detal.getHours().multiply(labourRate);
    detal.setHoursCost(hoursCost);
    detal.setSubtotal(hoursCost.add(detal.getMaterialCost()));//小计
    detal.setHandlingSuggestion("");//处理意见,默认为空
    sumtotal=sumtotal.add(detal.getSubtotal()); //修箱金额每次叠加
    
    ecmRepiarEstmateDetals.add(detal);//这个对象要存
    }
    
    iDetal++;// 下一行
    }
    newEcmRepairEstmate.setTotalAmout(sumtotal);//最后加上修箱金额
    newEcmRepairEstmate.setEcmRepiarEstmateDetals(ecmRepiarEstmateDetals); //详表集合
    }
    return newEcmRepairEstmate;
    }
    
    /**
    * 判断Excel版本
    * @param filePath
    * @return
    */
    public static boolean isExcel2003(String filePath) {
    
    return filePath.matches("^.+\\.(?i)(xls)$");
    
    }
    
    /**
    * 日期转数字
    *
    * @param time
    * @return
    * @throws IOException
    */
    public String dateChange(String time) throws IOException {
    
    time = time.replace("-", "").replace(":", "").replace(" ", "");
    
    return time;
    
    }
    
    /**
    * 以字符的方式返回当前sheet中的一个cell
    *
    * @param cell
    * @return
    */
    private String getCellAsString(Cell cell) {
    // 以字符中方式返回当前sheet中的一个cell
    String cellStr = "";
    
    if (cell != null) {
    try {
    switch (cell.getCellType()) {
    case 0: { // CELL_TYPE_NUMERIC
    if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
    SimpleDateFormat sdf = null;
    if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
    .getBuiltinFormat("h:mm")) {
    sdf = new SimpleDateFormat("HH:mm");
    Date date = cell.getDateCellValue();
    cellStr = sdf.format(date);
    } else {// 日期
    sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date = cell.getDateCellValue();
    cellStr = sdf.format(date);
    }
    } else {
    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    cellStr = cell.toString();
    
    // cellStr=String.valueOf(cellValue_int);
    // cellStr =
    // Double.toString(cell.getNumericCellValue());
    // cell.getStringCellValue();
    }
    
    break;
    }
    case 1: { // CELL_TYPE_STRING
    cellStr = cell.getStringCellValue();
    break;
    }
    case 2: { // CELL_TYPE_FORMULA DATE(),USDOLLAR(),SUM()
    String formula = cell.getCellFormula();
    if (formula.indexOf("DATE(") >= 0) {
    cellStr = HSSFDateUtil.getJavaDate(
    cell.getNumericCellValue()).toString();
    } else if (formula.indexOf("SUM(") >= 0) {
    cellStr = Double.toString(cell.getNumericCellValue());
    } else {
    cellStr = cell.getStringCellValue();
    }
    break;
    }
    default: {
    cellStr = new String("");
    }
    if (cellStr == null) {
    cellStr = "";
    }
    } // end switch
    } catch (Exception ex) {
    cellStr = "";
    }
    }
    
    return cellStr.trim();
    }
    /**
    * 看是不是空
    * @param o
    * @return
    */
    private boolean isEmpty(Object o) {
    return o != null ? o.toString().trim().length() == 0 : true;
    }
    
    /**
    * 保存导入的估计单到数据库
    * @return
    */
    public boolean saveImportEcmRepairEstmate(EcmRepairEstmate ecmRepairEstmate){
    JdbcTemplate jdbcTemplate=this.getJdbcTemplate();
    //先加主表
    String sql="insert into ECM_REPAIR_ESTMATE values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    Object[] params=new Object[]{
    ecmRepairEstmate.getBillNo(),
    ecmRepairEstmate.getCreateTimeZone(),
    ecmRepairEstmate.getFeeStatus(),
    ecmRepairEstmate.getProductName(),
    ecmRepairEstmate.getTotalAmout(),
    ecmRepairEstmate.getCreator(),
    1,
    ecmRepairEstmate.getStatus(),
    ecmRepairEstmate.getGateInDate(),
    ecmRepairEstmate.getCreateOffice(),
    ecmRepairEstmate.getMoveNo(),
    ecmRepairEstmate.getPrincipalGroupCode(),
    ecmRepairEstmate.getConfirmMan(),//修箱确认人代码
    ecmRepairEstmate.getRepairEstmateNo(),
    ecmRepairEstmate.getEcmRepairEstmateId(),
    ecmRepairEstmate.getRepairFinishDate(),//修箱完成时间
    ecmRepairEstmate.getLastModifyor(),
    ecmRepairEstmate.getCreateTime(),//创建时间
    ecmRepairEstmate.getLastModifyTime(),//最后修改时间
    ecmRepairEstmate.getConfirmMan(),
    ecmRepairEstmate.getSkNo(),
    ecmRepairEstmate.getRepairManCode(),
    ecmRepairEstmate.getRepairMan(),
    ecmRepairEstmate.getRepairDepot(),
    ecmRepairEstmate.getLastModifyOffice(),
    ecmRepairEstmate.getRemark(),
    ecmRepairEstmate.getLabourRate(),
    ecmRepairEstmate.getTankNo(),
    ecmRepairEstmate.getNewFlag(),
    ecmRepairEstmate.getLastModifyTimeZone(),
    ecmRepairEstmate.getRepairDepotCode(),
    ecmRepairEstmate.getProductCode(),
    ecmRepairEstmate.getCreateBillDate(),
    ecmRepairEstmate.getConfrimDate(),
    ecmRepairEstmate.getVersion()
    };
    int frist=jdbcTemplate.update(sql, params);
    
    return true;
    }
    
    public int saveImportDetil(EcmRepairEstmate ecm,final Set<EcmRepiarEstmateDetal> ecmRepiarEstmateDetals){
    JdbcTemplate jdbcTemplate=this.getJdbcTemplate();
    
    String sql="insert into ECM_REPAIR_ESTMATE_DETAIL values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    List<Object[]> parameters = new ArrayList<Object[]>();
    
    //遍历子表
    for (EcmRepiarEstmateDetal detal : ecmRepiarEstmateDetals) {
    BigDecimal materialCostAvg=new BigDecimal(0);
    BigDecimal hoursCostAvg=new BigDecimal(0);
    StringBuffer materialAvg=new StringBuffer();
    StringBuffer hoursAvg=new StringBuffer();
    materialAvg.append("select round( avg(nvl(t.material_cost,0)),2) from Ecm_Repair_Estmate_Detail t , ecm_repair_estmate e ");
    materialAvg.append(" where t.ecm_repair_estmate_id=e.ecm_repair_estmate_id");
    materialAvg.append(" and t.repair_comp_name='"+detal.getRepairCompName()+"' and t.repair_item_name='"+detal.getRepairItemName()+"' and t.repair_damage_code='"+detal.getRepairDamageCode()+"' and t.repair_code='"+detal.getRepairCode()+"'");
    materialAvg.append(" and e.new_flag='Y' and t.status='Y' and e.repair_depot_code='"+ecm.getRepairDepotCode()+"'");
    materialAvg.append(" group by t.repair_comp_name,t.repair_item_name,t.repair_damage_code,t.repair_code");
    
    hoursAvg.append("select round( avg(nvl(t.hours,0)),2) from Ecm_Repair_Estmate_Detail t , ecm_repair_estmate e ");
    hoursAvg.append(" where t.ecm_repair_estmate_id=e.ecm_repair_estmate_id");
    hoursAvg.append(" and t.repair_comp_name='"+detal.getRepairCompName()+"' and t.repair_item_name='"+detal.getRepairItemName()+"' and t.repair_damage_code='"+detal.getRepairDamageCode()+"' and t.repair_code='"+detal.getRepairCode()+"'");
    hoursAvg.append(" and e.new_flag='Y' and t.status='Y' and e.repair_depot_code='"+ecm.getRepairDepotCode()+"'");
    hoursAvg.append(" group by t.repair_comp_name,t.repair_item_name,t.repair_damage_code,t.repair_code");
    
    List<String> list;
    list=jdbcTemplate.queryForList(materialAvg.toString(),String.class);
    if(list.size()==1){
    materialCostAvg=new BigDecimal(list.get(0));
    }else {
    materialCostAvg=new BigDecimal(0);
    }
    list=jdbcTemplate.queryForList(hoursAvg.toString(),String.class);
    if(list.size()==1){
    hoursCostAvg=new BigDecimal(list.get(0));
    }else {
    hoursCostAvg=new BigDecimal(0);
    }
    
    
    parameters.add(new Object[] {
    nowtime,
    ecm.getEcmRepairEstmateId(),
    detal.getRepairCodeName(),
    hoursCostAvg,
    detal.getHoursCost(),
    detal.getRepairItemCode(),
    offceCode,
    offceCode,
    detal.getEcmRepairEstmateDetailId(),
    detal.getRemark(),
    detal.getSubtotal(),
    detal.getRepairCode(),
    1,//自带的版本号
    detal.getRepairCompName(),
    detal.getRepairDamageName(),
    detal.getPrincipalGroupCode(),
    detal.getRepairCompCode(),
    nowtime,
    detal.getCreateTimeZone(),
    detal.getStatus(),
    detal.getHours(),
    detal.getLastModifyor(),
    detal.getMaterialCost(),
    materialCostAvg,
    detal.getRepairItemName(),
    detal.getCreator(),
    detal.getLastModifyTimeZone(),
    detal.getRepairDamageCode(),
    detal.getHandlingSuggestion()
    }
    );
    }
    jdbcTemplate.batchUpdate(sql, parameters);
    return 1;
    }
    
    
    /**
    * 保存导入的估计单到文件、数据库
    * @param inputStream
    * @return
    */
    public String writeImportEcmRepairEstmate(String id,CommonsMultipartFile file){
    InputStream is=null;
    FileOutputStream fileout=null;
    String fName="";
    try {
    String fileName=file.getOriginalFilename();
    int indexdot = fileName.indexOf(".");
    String suffix = fileName.substring(indexdot);
    
    fName = fileName.substring(0,fileName.lastIndexOf("."));
    fName = fName + "_" +dateChange(new Date().toLocaleString());
    fName = fName + suffix;
    String local1="C://STOLT_FTP_FILES";
    String local2="/uploadFile/ecm/ImportEcmRepairEstmate/";
    //加上时间未完成
    is=file.getInputStream();
    //如果文件夹不存在则创建
    File dir =new File(local1+local2);
    if(!dir.exists()){
    dir.mkdirs();
    }
    fileout = new FileOutputStream(new File(local1+local2+fName));
    int temp; // 一个一个字节的读取并写入
    while ((temp = is.read()) != (-1)) {
    fileout.write(temp);
    }
    fileout.flush();
    fileout.close();
    //文件保存完了,开始存数据库
    
    
    //保存现有文件信息
    SysDownloadd sysDownloadd = new SysDownloadd();
    sysDownloadd.setAttachmentName(fileName); //文件名
    sysDownloadd.setAttachmentPath(local2+fName);//数据库保存路径的文件名也要加上id字段
    
    //根据文件名称,文件类别,文件类型和最新标识查询是否存在数据。如果存在,将以前的数据变为不是最新版本,再将当前数据变为最新版本插入
    /* SysDownloaddExample sysDownLoadExample = SysDownloaddExample.create();
    sysDownLoadExample.and().andAttachmentNameEqualTo(fileName).andAttachmentTypeEqualTo(fileType).andFiletoTypeEqualTo(filetoType).andNewFlagEqualTo(new BigDecimal("1"));
    
    List<SysDownloadd> listSysDownLoadd = sysDownloaddService.find(sysDownLoadExample);
    
    if(listSysDownLoadd.size() > 0){
    SysDownloadd sysDownloaddOld = listSysDownLoadd.get(0);
    sysDownloaddOld.setNewFlag(new BigDecimal(0));
    sysDownloaddOld.setRowStatus(BaseObject.ROWSTATUS_MODIFIED);
    sysDownloaddService.update(sysDownloaddOld);
    }*/
    sysDownloadd.setAttachmentType(suffix);
    sysDownloadd.setIpfCcmUploaderId(UUID.randomUUID().toString());
    sysDownloadd.setSourceOrderId(id);//和修箱估价单附件关联的字段
    sysDownloadd.setAttachmentNameModel("ecm");
    sysDownloadd.setNewFlag(new BigDecimal("1"));
    sysDownloadd.setFileSize(String.valueOf(file.getSize()));
    sysDownloadd.setFiletoType("估价单附件");
    sysDownloadd.setCreator(sysUser.getUserNameCn());
    sysDownloadd.setCreateTime(nowtime);
    //sysDownloadd.setCreator();
    //sysDownloadd.setRowStatus(BaseObject.ROWSTATUS_ADDED);
    JdbcTemplate jdbcTemplate=this.getJdbcTemplate();
    //先加主表
    String sql="insert into IPF_CCM_UPLOADER (ATTACHMENT_NAME,ATTACHMENT_PATH,ATTACHMENT_TYPE,IPF_CCM_UPLOADER_ID,SOURCE_ORDER_ID,ATTACHMENT_NAME_MODEL,NEW_FLAG,FILE_SIZE,FILETO_TYPE,CREATOR,CREATE_OFFICE,CREATE_TIME) values(?,?,?,?,?,?,?,?,?,?,?,?)";
    Object[] params=new Object[]{
    sysDownloadd.getAttachmentName(),
    sysDownloadd.getAttachmentPath(),
    sysDownloadd.getAttachmentType(),
    sysDownloadd.getIpfCcmUploaderId(),
    sysDownloadd.getSourceOrderId(),
    sysDownloadd.getAttachmentNameModel(),
    sysDownloadd.getNewFlag(),
    sysDownloadd.getFileSize(),
    sysDownloadd.getFiletoType(),
    sysUser.getUserName(),
    offceCode,
    nowtime
    
    };
    int frist=jdbcTemplate.update(sql, params);
    
    
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    
    if (is != null) {
    try {
    is.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    return fName;
    }
    
    @Override
    public boolean pending(String[] ecmRepairEstmateId) {
    if(ecmRepairEstmateId != null && ecmRepairEstmateId.length > 0){
    for(String id : ecmRepairEstmateId){ //修改路径信息CONFIRM
    EcmRepairEstmate ecmRepairEstmate = ecmRepairEstmateService.get(id);
    if(ecmRepairEstmate != null){
    ecmRepairEstmate.setRowStatus(BaseObject.ROWSTATUS_MODIFIED);
    ecmRepairEstmate.setFeeStatus("PENDING");
    ecmRepairEstmateService.update(ecmRepairEstmate);
    }
    
    }
    }
    return false;
    }
    
    @Override
    public boolean confirm(String[] ecmRepairEstmateId) {
    boolean falg=true;
    
    
    if(ecmRepairEstmateId != null && ecmRepairEstmateId.length > 0){
    
    for (String id : ecmRepairEstmateId) {
    for (EcmRepiarEstmateDetal detal : ecmRepairEstmateService.getEcmRepiarEstmateDetals(ecmRepairEstmateService.get(id))) {
    if("R".equals(detal.getStatus())){ //有重新提交的不能confirm
    falg=false;
    }
    }
    }
    
    if (falg) {
    for (String id : ecmRepairEstmateId) { // 修改路径信息CONFIRM
    EcmRepairEstmate ecmRepairEstmate = ecmRepairEstmateService
    .get(id);
    if (ecmRepairEstmate != null) {
    ecmRepairEstmate
    .setRowStatus(BaseObject.ROWSTATUS_MODIFIED);
    ecmRepairEstmate.setFeeStatus("CONFIRM");
    ecmRepairEstmateService.update(ecmRepairEstmate);
    }
    
    }
    }
    }
    
    return falg;
    }
    /**
    * 重新导入估价单
    */
    @Override
    public Map<String, String> againimportExcel(CommonsMultipartFile file,String ecmRepairEstmateId) {
    EcmRepairEstmate old = ecmRepairEstmateService.get(ecmRepairEstmateId);//获取旧估价单
    Map<String, String> rsmap=new HashMap<String, String>();//返回值的集合
    try {
    EcmRepairEstmate newEcmRepairEstmate =verifyExcel(file, old);
    
    
    if(StringUtils.isEmpty(errorInfo1)&&StringUtils.isEmpty(errorInfo2)){
    //如果解析没错,就开始存数据库
    saveImportEcmRepairEstmate(newEcmRepairEstmate);
    //开始存详表
    saveImportDetil(newEcmRepairEstmate,newEcmRepairEstmate.getEcmRepiarEstmateDetals());
    //存完记得文件也用输出流保存
    writeImportEcmRepairEstmate(newEcmRepairEstmate.getEcmRepairEstmateId(),file);
    
    rsmap.put("ecmid", newEcmRepairEstmate.getEcmRepairEstmateId());
    old.setRowStatus(BaseObject.ROWSTATUS_MODIFIED);
    old.setStatus("INVALID");//旧的设置成失效
    old.setNewFlag("N");
    ecmRepairEstmateService.update(old);//旧的保存
    JdbcTemplate jdbcTemplate = this.getJdbcTemplate();
    //把上一个版本的设为失效 不是最新版本
    //为了保险起见
    jdbcTemplate.update("update ecm_repair_estmate e set e.status='INVALID',e.new_flag='N' where e.repair_estmate_no='"+newEcmRepairEstmate.getRepairEstmateNo()+"' and e.version='"+newEcmRepairEstmate.getVersion().add(new BigDecimal(-1))+"'");
    }else{
    rsmap.put("errorInfo1", errorInfo1);
    rsmap.put("errorInfo2", errorInfo2.toString());
    }
    System.err.println("重新导入成功");
    } catch (NullPointerException e) {
    rsmap.put("errorExcel", "请根据模板文件导入!");
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    if (is != null) {
    try {
    is.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    return rsmap;
    
    
    }
    
    /**
    * 验证日期是否合法
    * @param str
    * @return
    */
    public boolean isValidDate(String str) {
    boolean convertSuccess=true;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    try {
    format.setLenient(false);
    format.parse(str);
    } catch (Exception e) {
    // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
    convertSuccess=false;
    }
    return convertSuccess;
    }
    /**
    * 删除的方法
    */
    @Override
    public boolean delete(String[] ids) {
    List<String> ecmRepairEstmateIds = Lists.newArrayList(ids);
    
    for (String string : ecmRepairEstmateIds) {
    EcmRepairEstmate estmate= ecmRepairEstmateService.get(string);
    if (!("PENDING".equals(estmate.getFeeStatus())&&"OPEN".equals(estmate.getStatus()))) {
    return false;//只能删除OPEN PENDING
    }
    }
    EcmRepairEstmateExample ecmRepairEstmateExample = EcmRepairEstmateExample.create();
    ecmRepairEstmateExample.and().andCreateCondition(EcmRepairEstmate.ECMREPAIRESTMATEID,"ecmRepairEstmateId",Operation.IN,Arrays.asList(ids));
    if (!ecmRepairEstmateIds.isEmpty())
    {
    fileService.deleteWithParent(ecmRepairEstmateIds);
    }
    if (!ecmRepairEstmateIds.isEmpty())
    {
    detalService.deleteWithParent(ecmRepairEstmateIds);
    }
    this.deleteByExample(ecmRepairEstmateExample);
    return true;
    }
    
    @Override
    public EcmRepairEstmate deleteBill(String billNo,String ecmid) {
    JdbcTemplate jdbcTemplate=this.getJdbcTemplate();
    String billid="";
    String sqlString="select b.ecm_repair_bill_id,b.status from ECM_REPAIR_BILL b where b.repair_bill_no='"+billNo+"'";
    List rowlist=jdbcTemplate.queryForList(sqlString);
    Iterator it=rowlist.iterator();
    if(it.hasNext()) {
    Map result=(Map)it.next();
    if("Y".equals(result.get("STATUS"))){
    return null;
    }else {
    billid=result.get("ECM_REPAIR_BILL_ID").toString();
    }
    
    }
    if (!"".equals(billid)) {
    
    EcmRepairEstmate ecm=ecmRepairEstmateService.get(ecmid);
    ecm.setRowStatus(BaseObject.ROWSTATUS_MODIFIED);
    ecm.setBillNo("");
    ecm.setCreateBillDate("");
    ecmRepairEstmateService.update(ecm);
    billService.delete(billid);
    return ecm;
    }
    
    return null;
    }
    }
    

    接口代码

    package com.gillion.platform.ecm.service;
    
    import java.io.InputStream;
    import java.util.Map;
    
    import org.springframework.web.multipart.commons.CommonsMultipartFile;
    
    import com.gillion.platform.ecm.domain.EcmRepairEstmate;
    import com.gillion.platform.ecm.domain.EcmRepairEstmateExample;
    import com.gillion.platform.framework.core.service.IBaseService;
    
    @SuppressWarnings("all")
    public interface EcmRepairEstmateServiceExt extends IBaseService<String,EcmRepairEstmate,EcmRepairEstmateExample>{
    
    /**
    * 自定义导入Excel
    * @param inputStream
    * @return
    */
    public Map<String, String> importExcel(CommonsMultipartFile file);
    
    /**
    * Pending
    * @param ecmRepairEstmateId
    * @return
    */
    public boolean pending(String[] ecmRepairEstmateId);
    
    /**
    * Confirm
    * @param ecmRepairEstmateId
    * @return
    */
    public boolean confirm(String[] ecmRepairEstmateId);
    
    /**
    * 重新导入估价单
    * @param file
    * @param ecmRepairEstmateId
    * @return
    */
    public Map<String, String> againimportExcel(CommonsMultipartFile file,String ecmRepairEstmateId);
    public boolean delete(String[] ids);
    
    /**
    * 根据对账单号删除对账单
    * @param billNo
    * @return
    */
    public EcmRepairEstmate deleteBill(String billNo,String ecmid);
    
    }
    

    在当前业务对象+ManageCtrl.js里面写自定义js内容

    $("[id='ecmRepairEstmate.importRepairEstmateEcmRepairEstmate']").after('<input type="file" id="EcmRepairEstmatefileUpload" style="display:none" onchange ="angular.element(this).scope().uploadFileEcmRepairEstmate()">');
    define([
    'angular',
    'underscore',
    'platform/ecm/ecmRepairEstmateManageBsCtrl', 'service/utils'
    ], function (angular, _, ecmRepairEstmateManageBsCtrl) {
    
    var Controller = inherit(function (options) {
    ecmRepairEstmateManageBsCtrl.call(this, options);
    
    var _this = this,
    $scope = _this.scope,
    $config = _this.config,
    injector = angular.element(document).injector(),
    Params = injector.get("Params"),
    $rootScope = injector.get("$rootScope"),
    $dataSourceManager = injector.get("$dataSourceManager"),
    $http = injector.get("$http"),
    $q = injector.get("$q"),
    $timeout = injector.get("$timeout"),
    RuleService = injector.get("RuleService"),
    AssociatePromiseService = injector.get("AssociatePromiseService"),
    GillionMsg = injector.get("GillionMsg"),
    GillionMsgService = injector.get("GillionMsgService"),
    Arrays = injector.get("Arrays");
    
    //TODO 自定义js函数
    /**
    * CONFIRM 管理页的 写在这里应该不会和编辑页的互相影响
    */
    $scope.confirmEcmRepairEstmate = function() {
    var param = {};
    var ids = Arrays.extract($scope.ecmRepairEstmateCheckedRows, 'ecmRepairEstmateId').join(',');
    if(ids.length == 0){
    GillionMsg.alert("提示","请选择记录!");
    return;
    }
    param.ids = ids;
    GillionMsg.confirm(null,'是否CONFIRM?',function(btn) {
    if (btn) {
    $http.post($config.ctx + '/ecmRepairEstmate/confirmljl',param).success(function(data){
    if (data.success != undefined && data.success == true){
    if(data.msg == "1"){
    $scope.getEcmRepairEstmatePages();
    GillionMsg.alert("提示","CONFIRM成功!");
    }else{
    GillionMsg.alert("提示","所选记录明细费用里有重新提交状态的记录!");
    }
    }
    });
    }
    });
    }
    
    //TODO 自定义js函数
    /**
    * PENDING 管理页的 写在这里应该不会和编辑页的互相影响
    */
    $scope.pendingEcmRepairEstmate = function() {
    var param = {};
    var ids = Arrays.extract($scope.ecmRepairEstmateCheckedRows, 'ecmRepairEstmateId').join(',');
    if(ids.length == 0){
    GillionMsg.alert("提示","请选择记录!");
    return;
    }
    param.ids = ids;
    GillionMsg.confirm(null,'是否PENDING?',function(btn) {
    if (btn) {
    $http.post($config.ctx + '/ecmRepairEstmate/pendingljl',param).success(function(data){
    if (data.success != undefined && data.success == true){
    $scope.getEcmRepairEstmatePages();
    GillionMsg.alert("提示","PENDING成功!");
    }
    });
    }
    });
    }
    
    //TODO 自定义js函数
    /**
    * 导入估价单 平台的按钮
    */
    $scope.importRepairEstmateEcmRepairEstmate = function() {
    
    //document.getElementById("EcmRepairEstmatefileUpload").click();
    $("#EcmRepairEstmatefileUpload").click();
    }
    
    /**
    * 下载估价单模板
    */
    $scope.downloadTemplateEcmRepairEstmate = function() {
    window.location.href = $config.ctx + '/ecmRepairEstmate/downloadFileExcel?fileName=123';
    }
    /**
    * 文件框改变时的方法
    * onchange ="angular.element(this).scope().uploadFileEcmRepairEstmateEcmRepairEstmate()"
    */
    $scope.uploadFileEcmRepairEstmate=function(){
    var file=$('#EcmRepairEstmatefileUpload')[0].files[0];
    var fileext=file.name.substring(file.name.lastIndexOf("."),file.name.length);
    if(file==""){
    GillionMsg.alert("提示","请选择要导入的Excel文件");
    }else{
    if(file.size>1024*1024*10){
    GillionMsg.alert("提示","文件大小不能超过10M");
    }else{
    if(fileext!='.xls'&&fileext!='.xlsx'){
    GillionMsg.alert("提示","只能导入Excel文件");
    }
    else{
    var myform = new FormData();
    myform.append('file',file);//../../../stolt
    $.ajax({
    url: $config.ctx +"/ecmRepairEstmate/uploadExcel",
    type: "POST",
    data: myform,
    contentType: false,
    processData: false,
    success: function (data) {
    if(data.errorExcel){
    GillionMsg.alert("提示",data.errorExcel);
    }else if(data.errorInfo1){
    GillionMsg.alert("提示",data.errorInfo1);
    }else if(data.errorInfo2){
    GillionMsg.alert("提示",data.errorInfo2);
    }else{
    GillionMsg.alert("提示","导入估价单成功");
    $scope.getEcmRepairEstmatePages();
    }
    },
    error:function(data){
    GillionMsg.alert("提示","导入异常,请与开发者联系");
    }
    });
    
    }
    }
    }
    $("#EcmRepairEstmatefileUpload").val("");
    
    };
    
    
    /**
    * 重写删除,做校验
    * TODO GLPaaS生成
    * 批量删除修箱估价单
    */
    $scope.deleteEcmRepairEstmates = function(){
    var ids = Arrays.extract($scope.ecmRepairEstmateCheckedRows, 'ecmRepairEstmateId').join(',');
    if(ids.length == 0){
    GillionMsg.alert("提示","请选择要删除的记录!");
    return;
    }
    GillionMsg.confirm(null,'确认删除?',function(btn) {
    if (btn) {
    $scope._finishEditGridWrap($scope.ecmRepairEstmateGrid,$scope.ecmRepairEstmates,$scope);
    $http.post($config.ctx + '/ecmRepairEstmate/deletesljl',{ids : ids}).success(function(data){
    if (data.success != undefined && data.success == true) {
    
    $scope.getEcmRepairEstmatePages();
    
    if($scope._pageState) $scope._pageState.resetDataState();
    var gridVerifyArr = [ { scope:"$scope" ,grid:["ecmRepairEstmate"] }, { scope:"$scope" ,grid:["ecmRepiarEstmateFile"] ,loadOneToOneSubBoData:false }, { scope:"$scope" ,grid:["ecmRepiarEstmateDetal"] ,loadOneToOneSubBoData:false } ];
    _this.gridVerify({boName:"EcmRepairEstmate",scope:$scope,settings:gridVerifyArr});
    GillionMsg.alert("提示", data.msg);
    
    $timeout(function(){
    if($scope._pageState) $scope._pageState.resetDataState();
    });
    }
    
    });
    }
    });
    
    };
    
    this.scope.customThree = function () {
    alert("请配置方法实现");
    };
    
    this.scope.controlOneTestSysStBooking = function (aa, bb, cc) {
    alert('dfd');
    };
    },ecmRepairEstmateManageBsCtrl);
    
    var Proto = Controller.prototype;
    
    return Controller;
    });
    /*
    * $("[id='ecmRepairEstmate.importRepairEstmateEcmRepairEstmate']").after('<input type="file" id="EcmRepairEstmatefileUpload" style="display:none" onchange ="uploadFileEcmRepairEstmate()">');
    * function uploadFileEcmRepairEstmate() {
    var file=$('#EcmRepairEstmatefileUpload')[0].files[0];
    var fileext=file.name.substring(file.name.lastIndexOf("."),file.name.length)
    if(file==""){
    alert("请选择要导入的Excel文件");
    }else{
    if(file.size>1024*1024*10){
    alert("文件大小不能超过10M");
    }else{
    if(fileext!='.xls'&&fileext!='.xlsx'){
    alert("只能导入Excel文件");
    }
    else{
    var myform = new FormData();
    myform.append('file',file);
    $.ajax({
    url: "../../../stolt/ecmRepairEstmate/uploadExcel",
    type: "POST",
    data: myform,
    contentType: false,
    processData: false,
    success: function (data) {
    debugger;
    if(data.errorInfo1.length>0){
    alert(data.errorInfo1);
    }else if(data.errorInfo2.length>0){
    alert(data.errorInfo2);
    }else{
    alert("导入估价单成功");
    }
    },
    error:function(data){
    alert("导入异常,请与开发者联系");
    }
    });
    
    }
    }
    }
    $("#EcmRepairEstmatefileUpload").val("");
    
    }
    */
    

    4. 版本更新 4. 版本更新

    预发布.业务对象重名

    优化

  • 【导出配置数据】如果勾选的是引用数据,提示【请回原视图导出配置数据!】。
  • 【同步到目标数据库】如果勾选的是引用数据,提示【请回原视图导出配置数据!】。
  • 查询界面优化。颜色标识,使用新表格。
  • 维护界面优化。业务对象联想控件过滤调整及去掉字段模块名称。
  • 预发布.业务对象重名

    新功能

  • 需要支持一个对象可以配置多个POI导入导出【需求见禅道号 27082】
  • 5.3.0,2019.01.03

    新特性

  • 新导入方法配置