1、Controller

    @RequestMapping(value = "/importBlackCatLadingBill", method = RequestMethod.POST, produces = "multipart/form-data; charset=utf-8")@ApiOperation(httpMethod = "POST", value = "导入")public String importLadingbillData(@RequestParam("file") MultipartFile file, HttpServletRequest request) {return service.importCatData(request.getHeader("accountId"), file);}

2、Service层, 控制能够导入的类型,将导入时的信息存入对应的表中(可有可无,根据业务来写),最后解析Excel,将数据封装到对象并且保存导数据库中

    public String importCatData(String accountId, MultipartFile file) {ApiOutParamsInfo<Boolean> result = new ApiOutParamsInfo<Boolean>();LoginAccount loginAccount = (LoginAccount) redisUtil.hget("ACCOUNTINFO", accountId + "_login");TImportManagement tImportManagement = new TImportManagement();Map<String, Object> excelMap = new HashMap<>();
//        List<Object> list = null;
//      将导入文件的信息记录下来(可有可无,根据具体业务来写)tImportManagement.setImportPersion(loginAccount.getAccountName());tImportManagement.setFileName(file.getOriginalFilename());tImportManagement.setAffixId("");tImportManagement.setImportTime(new Timestamp(System.currentTimeMillis()));tImportManagement.setNumberOfReadFiles(1);tImportManagement.setImportStatus(0);tImportManagement.setDeleted(0);baseDao.save(tImportManagement);String fileName = file.getOriginalFilename();String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
//       判断文件后缀来判断该文件是否能够导入if (fileSuffix.equals("zip")) {result.setCode("2");result.setMsg("导入失败,不能传zip");result.setResult(false);return JSON.toJSONString(result);} else if (fileSuffix.equals("xls") || fileSuffix.equals("xlsx")) {try {excelMap = excelParseBlcakCat(POIPostalUtil.readCommonExcel2(file.getInputStream(), 0, 1));} catch (IOException e) {e.printStackTrace();}} else {result.setCode("2");result.setMsg("不支持上传" + fileSuffix + "类型文件");result.setResult(false);return JSON.toJSONString(result);}
//       if (list == null || list.size() < 1) {
//            result.setCode("0");
//            result.setMsg("导入失败更新数据条数未0");
//            result.setResult(false);
//            return JSON.toJSONString(result);
//        }
//      通过foreach 循环写入excel中的数据(每一行都时一个对象)for (TBlackCatInfo tBlackCatInfo : (List<TBlackCatInfo>) excelMap.get("list")) {//没有才插入baseDao.save(tBlackCatInfo);}if ((int) excelMap.get("count") == 2) {result.setCode("0");result.setMsg("导入成功");tImportManagement.setImportStatus(1);baseDao.update(tImportManagement);result.setResult(true);return JSON.toJSONString(result);} else {result.setCode("2");result.setMsg(String.valueOf(excelMap.get("msg")));tImportManagement.setImportStatus(2);baseDao.update(tImportManagement);return JSON.toJSONString(result);}}

4、将Excel解析成为List

  public static List<List<String>> readCommonExcel2(InputStream inputStream, Integer sheetPosition, Integer columnPosition) {List<String> columnList = null;List<List<String>> list = new ArrayList<List<String>>();Workbook wb = null;Sheet sheet = null;try {wb = WorkbookFactory.create(inputStream);sheet = wb.getSheetAt(sheetPosition); // 读取sheet 0int firstRowIndex = columnPosition;int lastRowIndex = sheet.getLastRowNum();boolean flag = false;for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { // 遍历行columnList = new ArrayList<String>();Row row = sheet.getRow(rIndex);if (row == null) {return list;}for (int i = 0; i < 50; i++) { // 遍历本次行的单元格,i为有多少列Cell cell = row.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);;cell.setCellType(CellType.STRING);if (i == 1) {if (CommUtil.toString(cell.toString()).equals("")) {flag = true;break;}}columnList.add(cell.toString());}if (flag) {break;}list.add(columnList);}} catch (Exception e) {e.printStackTrace();}return list;}

5、将Excel解析后的数据遍历后封装为为对象,然后存入数据库

    public Map<String, Object> excelParseBlcakCat(List<List<String>> lists) {Date date = new Date();Map<String, Object> map = new HashMap<>();List<TBlackCatInfo> tBlackCatInfos = new ArrayList<>();int successCount = 0;StringBuilder errMsg = new StringBuilder();Map<String, String> queryBillNoCheck = new HashMap<>();Map<String, String> custOrderNoCheck = new HashMap<>();Map<String, String> tradeNoCheck = new HashMap<>();
//  通过foreach遍历Excel中的数据,并且根据业务做对应的处理for (List<String> list : lists) {String str = JSON.toJSONString(lists);System.out.println(str);if (queryBillNoCheck.containsKey(list.get(1))) {errMsg.append("客户单号" + list.get(1) + "客户单号\n");continue;} else {queryBillNoCheck.put(list.get(1), list.get(1));String hql = "from TBlackCatInfo where waybillNum = :waybillNum";Map<String, Object> param = new HashMap<>();param.put("waybillNum", list.get(1));TBlackCatInfo tBlackCatInfo1 = (TBlackCatInfo) baseDao.getByHQL(hql, param);System.out.println("aa" + list.get(1) + "aa");System.out.println("aa" + tBlackCatInfo1 + "aa");if (tBlackCatInfo1 != null) {errMsg.append("客户单号" + list.get(1) + "单号重复\n");continue;}}if (custOrderNoCheck.containsKey(list.get(3))) {errMsg.append("日本单号" + list.get(3) + "单号重复\n");continue;} else {custOrderNoCheck.put(list.get(3), list.get(3));String hql = "from TBlackCatInfo where changeNum = :changeNum";Map<String, Object> param = new HashMap<>();param.put("changeNum", list.get(3));TBlackCatInfo tBlackCatInfo2 = (TBlackCatInfo) baseDao.getByHQL(hql, param);if (tBlackCatInfo2 != null) {errMsg.append("日本单号" + list.get(3) + "单号重复\n");continue;}}if (list.get(2) != null && list.get(2) != "" && list.get(2) != "null") {if (tradeNoCheck.containsKey(list.get(2))) {errMsg.append("换单号" + list.get(2) + "单号重复\n");continue;} else {tradeNoCheck.put(list.get(2), list.get(2));String hql = "from TBlackCatInfo where tradeNum = :tradeNum";
//                String hql = "from TBlackCatInfo where tradeNum = :waybillNum";Map<String, Object> param = new HashMap<>();param.put("tradeNum", list.get(2));TBlackCatInfo tBlackCatInfo2 = (TBlackCatInfo) baseDao.getByHQL(hql, param);if (tBlackCatInfo2 != null) {errMsg.append("换单号" + list.get(2) + "单号重复\n");continue;}}}
//            会员编号只能为数字和英文字母if (list.get(0).matches(LETTER_DIGIT_REGEX) != true) {errMsg.append("转单号" + list.get(3) + "会员编号只能为英文字母和数字\n");continue;}
//            地址验证TBlackCatInfo tBlackCatInfo = new TBlackCatInfo();boolean flag = false;String hql = "from TBlackCatMail t1 where t1.postCode= :postCode";Map<String, Object> params = new HashMap<String, Object>() {private static final long serialVersionUID = 7873919242529938351L;{put("postCode", list.get(11).replaceAll("-", ""));}};log.info("postCode ===> {}", params.get("postCode"));List<TBlackCatMail> tBlackCatMails = baseDao.getListByHQL(hql, params);log.info(String.format("tBlackCatMail ==> %s", JSON.toJSONString(tBlackCatMails)));String addressOne = EDIUtil.ToSBC(list.get(12));for (TBlackCatMail tBlackCatMail : tBlackCatMails) {String address = tBlackCatMail.getCity() + tBlackCatMail.getState() + tBlackCatMail.getStreet();if ("".equals(tBlackCatMail.getCity()) && tBlackCatMail.getCity() == null && "".equals(tBlackCatMail.getState())&& tBlackCatMail.getState() == null && "".equals(tBlackCatMail.getStreet()) && tBlackCatMail.getStreet() == null) {tBlackCatInfo.setReceAddOne(addressOne);tBlackCatInfo.setSimpleZipCode(tBlackCatMail.getPostCodeShort());tBlackCatInfo.setReceZipCode(list.get(11));flag = true;continue;} else {log.info("address{}" + address);log.info("addressOne{}" + addressOne);
//                    使用StartsWith验证addressOne是否以address开头if (addressOne.replace("の", "ノ").startsWith(address.replace("の", "ノ"))|| addressOne.replace("ノ", "の").startsWith(address.replace("ノ", "の"))) {// 判断在郊区后面有没有数字String addressAfter = addressOne.substring(address.length());log.info("addressAfter{}" + addressAfter);if (hasDigit(EDIUtil.ToDBC(addressAfter))) {// 派送地址1tBlackCatInfo.setReceAddOne(addressOne);tBlackCatInfo.setSimpleZipCode(tBlackCatMail.getPostCodeShort());tBlackCatInfo.setReceZipCode(list.get(11));flag = true;continue;}}}}if (!flag) {errMsg.append("转单号" + list.get(3) + "邮编对应的地址有误\n");continue;}
//        封装数据入库tBlackCatInfo.setIsEdi(0);tBlackCatInfo.setIsPrint((short) 0);tBlackCatInfo.setImportTime(new Timestamp(date.getTime()));tBlackCatInfo.setReceName(EDIUtil.ToSBC(list.get(9)));tBlackCatInfo.setArriveNameEn(EDIUtil.ToSBC(list.get(10)));tBlackCatInfo.setReceAddOne(EDIUtil.ToSBC(list.get(12)));tBlackCatInfo.setWeight(new BigDecimal(list.get(13)).setScale(1, BigDecimal.ROUND_HALF_UP).toString());
//            String sql = "select * from t_cat_post_code_config where post_code =:postCode";
//            Map<String, Object> param = new HashMap<>();
//            param.put("postCode", tBlackCatInfo.getReceZipCode().replace("-", ""));
//            Map<String, Object> rstMap = (Map<String, Object>) baseDao.getBySQL(sql, param);
//            if (rstMap != null) {
//                tBlackCatInfo.setSimpleZipCode(rstMap.get("post_code_short").toString());
//            }// 判断客户邮编格式对不对String[] mailCodeSplit = tBlackCatInfo.getReceZipCode().split("-");if (mailCodeSplit.length != 2 || mailCodeSplit[0].length() != 3 || mailCodeSplit[1].length() != 4) {errMsg.append("转单号" + list.get(3) + "邮编格式不对\n");continue;}tBlackCatInfo.setProductName(EDIUtil.ToSBC(list.get(19)));if (tBlackCatInfo.getProductName().length() > 25) {errMsg.append("转单号" + list.get(3) + "品名长度不能大于25");continue;}if (list.get(18) != null && !"".equals(list.get(18))) {tBlackCatInfo.setDeclareCurrency(list.get(18));}if (list.get(22) != null && !"".equals(list.get(22))) {tBlackCatInfo.setPrice(new BigDecimal(list.get(22)));}tBlackCatInfo.setCount(list.get(21));tBlackCatInfo.setTradeNum(list.get(2));tBlackCatInfo.setBoxCode(list.get(4));tBlackCatInfo.setReceiverTel(list.get(8));tBlackCatInfo.setPrintTimes(0);
//            tBlackCatInfo.setSenderName(EDIUtil.ToSBC(list.get(41)));
//            tBlackCatInfo.setDepAddOne(EDIUtil.ToSBC(list.get(42)));tBlackCatInfo.setSenderName(EDIUtil.ToSBC("LED&TBS CO.,ltd"));tBlackCatInfo.setDepAddOne(EDIUtil.ToSBC("大阪府泉南市新家2073-2"));tBlackCatInfo.setDepZipCode("590-0503");tBlackCatInfo.setWaybillNum(list.get(1));tBlackCatInfo.setChangeNum(list.get(3));tBlackCatInfo.setMemberNum(list.get(0));tBlackCatInfos.add(tBlackCatInfo);successCount++;}// 一条都未校验通过if (successCount == 0) {map.put("count", 0);// 部分校验通过} else if (successCount < lists.size()) {map.put("count", 1);} else {// 全部通过map.put("count", 2);}map.put("list", tBlackCatInfos);map.put("msg", errMsg.toString());return map;}// 判断一个字符串是否含有数字public static boolean hasDigit(String content) {boolean flag = false;Pattern p = Pattern.compile(".*\\d+.*");Matcher m = p.matcher(content);if (m.matches())flag = true;return flag;}

Excel文件导入数据相关推荐

  1. php上传查询excel到mysql_PHP上传Excel文件导入数据到MySQL数据库示例

    PHP上传Excel文件导入数据到MySQL数据库示例2020-06-20 00:34:11 最近在做Excel文件导入数据到数据库.网站如果想支持批量插入数据,可以制作一个上传Excel文件,导入里 ...

  2. php 上传excel到mysql_PHP上传Excel文件导入数据到MySQL数据库示例

    最近在做Excel文件导入数据到数据库.网站如果想支持批量插入数据,可以制作一个上传Excel文件,导入里面的数据内容到MySQL数据库的小程序. 要用到的工具: ThinkPHP:轻量级国产PHP开 ...

  3. asp.net C# 实现上传Excel文件导入数据到SQL Server 数据库

    前台代码,有点简单: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server&q ...

  4. 微信小程序云开发如何实现读取和下载excel文件导入数据到云数据库中?简单好理解

    一般我们在开发中会遇到通过excel文件一键导入数据的模板操作,我们在微信小程序中可以使用node-xlsx插件来解析excel文件的内容变成以json格式的数据返回. 在处理该操作的云函数中下载安装 ...

  5. php把excel导入mysql数据库中_PHP将Excel文件导入到MySQL数据库

    这篇文章主要介绍了PHP上传Excel文件导入数据到MySQL数据库示例,可以将Excel的数据写入到MySQL数据库中,感兴趣的同学可以了解一下. 最近在做Excel文件导入数据到数据库.网站如果想 ...

  6. 利用js-xlsx.js插件实现Excel文件导入并解析Excel数据成json数据格式

    <!--本文转载于网络,有太多一样的文章,不知道原作者是哪位了,就不注明出处了.这里记载下来,用于自己的学习借鉴--><!DOCTYPE html><html lang= ...

  7. php导入qq数据txt代码,/谁有能都实现将excel文件导入到数据中,并在php网页上显示的源码啊,有的发送1091932879@qq.com,谢谢!...

    PHP网页怎么导入Excel的数据 参码如下: // 1.引用ExcelReader类文 require_once 'Excel/reader.php'; // 2.实例化读取Excel类 $data ...

  8. abaqus python 读取文件_通过Python脚本从Abaqus中的excel文件导入幅度数据

    我在从excel文件导入幅度数据时在Abaqus中创建了以下宏.然后尝试运行此脚本以从同一个excel文件创建另一个幅度但不幸的是,我有以下错误.在这方面有人可以帮助我吗? 脚本: # Do not ...

  9. 如何将数据从Excel文件导入SQL Server数据库

    There are many ways to import data from an Excel file to a SQL Server database using: 有多种方法可以使用以下方法将 ...

最新文章

  1. 在github上创建自己的第一个项目仓库实录
  2. Self-Attention 加速方法一览:ISSA、CCNet、CGNL、Linformer
  3. RAC环境下的备份与恢复(一)
  4. ios 绘制线框_iOS 绘制虚线框
  5. php myadmin怎么用,关于apachemysqlphpmyadmin的安装与配置
  6. Ubuntu桌面版网络设置
  7. apache根据ip分发_腾讯广告进入“IP新融点”时代
  8. 全面认识UML-类图元素(java)
  9. 电脑怎么打字切换中文_Master of Typing in Chinese for Mac(中文打字大师)
  10. js根据数组中对象的多个属性值进行排序
  11. 三月活动之“桃花朵朵开 求爱上上签”
  12. Linux系统卸载文件系统(可用)
  13. Delphi调用C++写的dll示例
  14. 深入浅出MVC框架模式
  15. matlab图像的邻域操作,matlab图像的邻域操作与块操作 | 学步园
  16. UEditor快捷键
  17. 用matlab解决马尔可夫模型,MatLa工具箱b 马尔可夫模型的MatLab程序
  18. Android解决监听AppBarLayout的滑动状态来动态设置标题时报requestLayout() improperly called by错误问题
  19. IE8 使用 Oracle ERP
  20. 《SpringBoot官方文档》_笔记

热门文章

  1. git 查看冲突文件 unmerged paths
  2. 店铺销售管理系统有哪些用?该如何选?
  3. 天池龙珠训练营-机器学习学习笔记-03 LightGBM 分类
  4. 【为宏正名】本应写入教科书的“世界设定”
  5. 联想逆势增长,成手机市场又一实力黑马
  6. 【数字图像处理与python】自定义三维数组转换为彩色图像、自定义二维数组转为灰度图像
  7. linux 安装locate命令,Linux 中的 locate 命令详解
  8. Android操作系统发展史
  9. KnockoutJS by Example 免积分下载
  10. 几个目前(2022-10-7)免费可用的IP属地查询接口