import org.springframework.web.multipart.MultipartFile;@ApiOperation("导入")@PostMapping("/acct/import")public Result importAdminUser(@RequestPart("file") MultipartFile file) {try {List<String> strings = bookSetService.importAdminUser(file);return new Result(0000, "上传成功", strings);} catch (Exception e) {log.error(e.getMessage(), e);log.error(e.getMessage(), e);return new Result(9999, e.getMessage(), e.getMessage());}}
@Overridepublic List<String> importAdminUser(MultipartFile file) throws Exception{if (file == null || file.getSize() <= 0) {throw new InvalidParamException("文件是空的");}//1,解析文件,获取数据List<AcctInfo> acctListsList<AcctInfo> acctLists = new LinkedList<>();ImportUtils importUtil = new ImportUtils<AcctInfo>(AcctInfo.class);String filename = file.getOriginalFilename();if (filename.endsWith(".xls")) {acctLists = importUtil.readExcel2003(file.getInputStream(), 2, 0);} else if (filename.endsWith(".xlsx")) {acctLists = readExcel2007(file.getInputStream(), 2, 0);}else {throw new InvalidParamException("文件格式有误");}// 未读出导数据则返回if (grp.pt.util.CollectionUtils.isListEmpty(acctLists)) {throw new NoneDataException("未检测到数据");}//2,校验格式正确性List<String> resInfo = new ArrayList<>(); //返回信息for (int i = 0; i < acctLists.size(); i++) {boolean boo = true;AcctInfo acctVo = acctLists.get(i);//编码if (StringUtil.isNull(acctVo.getCode()) || StringUtil.isEmpty(acctVo.getCode())) {resInfo.add("第" + (i + 3) + "行【编码】为空");boo = false;}//名称if (StringUtil.isNull(acctVo.getName()) || StringUtil.isEmpty(acctVo.getName())) {resInfo.add("第" + (i + 3) + "行【名称】为空");boo = false;} else {if (acctVo.getName().length() >= 100) {resInfo.add("第" + (i + 3) + "行【名称】长度不能超过100");boo = false;}}}//3,导入if (acctLists.size() > 0) {String s = importAcctList(acctLists);resInfo.add(s);} else {resInfo.add("共计成功导入0条");}return resInfo;}
public static List<AcctInfo> readExcel2007(InputStream is, int rowIndex, int cellIndex) throws IOException {List<AcctInfo> list = new LinkedList<>();//创建工作簿XSSFWorkbook workbook = new XSSFWorkbook(is);//读取第一个工作表XSSFSheet sheet = workbook.getSheetAt(0);//System.out.println("sheet对象:" + sheet);//获取最后一行的num,即总行数。此处从0开始计数int maxRow = sheet.getLastRowNum();log.info("总行数为:" + maxRow);for (int row = 1; row <= maxRow; row++) {int maxRol = sheet.getRow(row).getLastCellNum();log.info("--------第" + row + "行的数据如下--------");AcctInfo acctInfo = new AcctInfo();for (int rol = 0; rol < maxRol; rol++){String str = sheet.getRow(row).getCell(rol) + " ";switch (rol) {case 0://System.out.println("0---------" + sheet.getRow(row).getCell(rol) + "");acctInfo.setId(Integer.parseInt(str.substring(0,str.length()-3)));break;case 1://System.out.println("1---------" + sheet.getRow(row).getCell(rol) + " ");acctInfo.setCode(str);break;case 2://System.out.println("2---------" + sheet.getRow(row).getCell(rol) + " ");acctInfo.setName(str);break;case 3://System.out.println("3---------" + sheet.getRow(row).getCell(rol) + "");acctInfo.setTenantId(Long.parseLong(str.substring(0,str.length()-3)));break;default://System.out.println("4---------" + sheet.getRow(row).getCell(rol) + "");acctInfo.setBooksetType(Long.parseLong(str.substring(0,str.length()-3)));break;}}list.add(acctInfo);}return list;}
@Transactionalpublic String importAcctList(List<AcctInfo> acctLists) {if (grp.pt.util.CollectionUtils.isListEmpty(acctLists)) {return "共计成功导入0条";}try {if (acctLists.size() > 0) {bookSetDao.insertUser(acctLists);}} catch (Exception e) {return "导入失败--" + e.getMessage();}return "共成功导入" + acctLists.size() + "条";}
public void insertUser(List<AcctInfo> acctLists) {if (CollectionUtils.isListEmpty(acctLists)) {logger.warn("insertUser() userPos is null");return;}/** 适配mysql/oracle不同环境连接驱动的不同sql语法*/String database = getDatabase();if (DATABASE_ORACLE.equalsIgnoreCase(database) || "postgre".equalsIgnoreCase(database) || DATABASE_POLARDB.equalsIgnoreCase(database) || "dm".equalsIgnoreCase(database)) {List<AcctInfo> executeList = new LinkedList<>();for (int i = 0; i < acctLists.size(); ++i) {executeList.add(acctLists.get(i));if (executeList.size() % 100 == 0) {executeInsertUser(executeList);executeList = new ArrayList();}}if (executeList.size() > 0) {executeInsertUser(executeList);}} else if (DATABASE_MYSQL.equalsIgnoreCase(database)) {String sql = " INSERT INTO GAP_BOOK_SET( ID, CODE, NAME) VALUES(?, ?, ?)";batchExecute(sql, "id+code+name", acctLists);}}
/*** <p>批量执行新增* @param acctLists 账套列表*/private void executeInsertUser(List<AcctInfo> acctLists) {List<Object> params = new LinkedList<>();StringBuffer sql = new StringBuffer(128);sql.append(" INSERT INTO GAP_BOOK_SET( ID, CODE, NAME, IS_DELETED ) ");for (int i = 0; i < acctLists.size(); i++) {if (i == 0) {sql.append(" SELECT ?, ?, ? ,? FROM DUAL ");} else {sql.append(" UNION ALL SELECT ?, ?, ? ,? FROM DUAL ");}params.add(acctLists.get(i).getId());params.add(acctLists.get(i).getCode());params.add(acctLists.get(i).getName());params.add(1);}execute(sql.toString(), params.toArray());}
:::success
:::
public int[] batchExecute(String sql, String para, List list) {String[] paras = para.split("\\+");if ("MySQL".equals(this.dataBaseType)) {list = changeEmptyValueForMySQL(list);sql = DbFeatureFactory.GetFeature().translateSQL(sql);}return this.excuteBatch(sql, new CommonBatchSetter(paras, list));}
:::info
我们看一下return this.excuteBatch(sql, new CommonBatchSetter(paras, list));方法
:::
public int[] excuteBatch(String sql, BatchPreparedStatementSetter pss) {sql = DbFeatureFactory.GetFeature().translateSQL(sql);int[] result = this.jdbcTemplate.batchUpdate(sql, pss);return result;}
:::info
我们看一下this.jdbcTemplate.batchUpdate(sql, pss);方法
这是org.springframework.jdbc.core.JdbcTemplate提供的方法
我们看一下这个方法的参数**public int_[] _**batchUpdate**_(_**String sql, **final **BatchPreparedStatementSetter pss**_) _throws **DataAccessException **_{_**
:::
:::info
:::
