KpiComputeImportServiceImpl.java 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. package com.kcim.service.impl;
  2. import cn.hutool.core.date.DatePattern;
  3. import cn.hutool.core.date.DateTime;
  4. import cn.hutool.core.date.DateUtil;
  5. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  6. import com.kcim.common.constants.Constant;
  7. import com.kcim.common.constants.NumberConstant;
  8. import com.kcim.common.exception.CostException;
  9. import com.kcim.common.file.MinioConfig;
  10. import com.kcim.common.file.MinioFileUtil;
  11. import com.kcim.common.util.DateUtils;
  12. import com.kcim.common.util.PageUtils;
  13. import com.kcim.common.util.UserContext;
  14. import com.kcim.dao.model.KpiComputeImport;
  15. import com.kcim.dao.repository.KpiComputeImportRepository;
  16. import com.kcim.service.CenterService;
  17. import com.kcim.service.KpiComputeImportService;
  18. import com.kcim.vo.CommonTitleVo;
  19. import com.kcim.vo.DictDataVo;
  20. import com.kcim.vo.SheetImportResultVO;
  21. import com.kcim.vo.UserInfoVO;
  22. import lombok.SneakyThrows;
  23. import lombok.extern.slf4j.Slf4j;
  24. import org.apache.commons.io.FileUtils;
  25. import org.apache.ibatis.jdbc.SqlRunner;
  26. import org.apache.poi.hssf.usermodel.HSSFDateUtil;
  27. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  28. import org.apache.poi.ss.usermodel.*;
  29. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  30. import org.springframework.beans.factory.annotation.Value;
  31. import org.springframework.stereotype.Service;
  32. import org.springframework.transaction.annotation.Propagation;
  33. import org.springframework.transaction.annotation.Transactional;
  34. import org.springframework.util.CollectionUtils;
  35. import org.springframework.web.multipart.MultipartFile;
  36. import java.io.File;
  37. import java.io.FileInputStream;
  38. import java.io.IOException;
  39. import java.io.InputStream;
  40. import java.sql.Connection;
  41. import java.sql.DriverManager;
  42. import java.sql.SQLException;
  43. import java.util.*;
  44. import java.util.stream.Collectors;
  45. /**
  46. * @program: CostAccount
  47. * @description:
  48. * @author: Wang.YS
  49. * @create: 2024-06-03 13:58
  50. **/
  51. @Service("kpiComputeImportService")
  52. @Slf4j
  53. public class KpiComputeImportServiceImpl implements KpiComputeImportService {
  54. private final KpiComputeImportRepository repository;
  55. private final MinioConfig minioConfig;
  56. private final MinioFileUtil minioFileUtil;
  57. private final CenterService centerService;
  58. @Value("${spring.datasource.driver-class-name}")
  59. private String driver;
  60. @Value("${spring.datasource.url}")
  61. private String url;
  62. @Value("${spring.datasource.username}")
  63. private String username;
  64. @Value("${spring.datasource.password}")
  65. private String password;
  66. public KpiComputeImportServiceImpl(KpiComputeImportRepository repository, MinioConfig minioConfig, MinioFileUtil minioFileUtil, CenterService centerService) {
  67. this.repository = repository;
  68. this.minioConfig = minioConfig;
  69. this.minioFileUtil = minioFileUtil;
  70. this.centerService = centerService;
  71. }
  72. /**
  73. * 查询导入列表
  74. *
  75. * @param current 当前页
  76. * @param pageSize 页容量
  77. * @param computeDate 核算年月
  78. * @param tableName 表名
  79. * @return 导入列表
  80. */
  81. @Override
  82. public Object getList(Integer current, Integer pageSize, String computeDate, String tableName) {
  83. List<UserInfoVO> centerEmployee = centerService.getCenterUserInfo(null);
  84. Map<Long, String> userName = centerEmployee.stream().collect(Collectors.toMap(UserInfoVO::getId, UserInfoVO::getName, (a, b) -> b));
  85. DictDataVo dict = centerService.getDict(Constant.SPECIAL_SHEET_MAP);
  86. if (Objects.isNull(dict)) {
  87. throw new CostException("未找到特殊项目导入字典");
  88. }
  89. List<DictDataVo> dataVoList = dict.getDataVoList();
  90. if (CollectionUtils.isEmpty(dataVoList)) {
  91. throw new CostException("未找到特殊项目导入字典");
  92. }
  93. Map<String, String> dictionaryCodeNameMap = dataVoList.stream().collect(Collectors.toMap(DictDataVo::getCode, DictDataVo::getName, (a, b) -> b));
  94. Page<KpiComputeImport> page = repository.getPage(current, pageSize, computeDate, tableName);
  95. List<KpiComputeImport> list = page.getRecords();
  96. if (CollectionUtils.isEmpty(list)) {
  97. return new PageUtils(new ArrayList<>(), NumberConstant.ZERO, pageSize, current);
  98. }
  99. for (KpiComputeImport computeImport : list) {
  100. computeImport.setCreateUserName(userName.get(Long.valueOf(computeImport.getCreateUser())));
  101. computeImport.setTableNameDisplay(dictionaryCodeNameMap.get(computeImport.getTableName()));
  102. }
  103. return new PageUtils(list, Math.toIntExact(page.getTotal()), pageSize, current);
  104. }
  105. /**
  106. * @return
  107. */
  108. @Override
  109. public Object getTableList() {
  110. DictDataVo dict = centerService.getDict(Constant.SPECIAL_SHEET_MAP);
  111. if (Objects.isNull(dict)) {
  112. throw new CostException("未找到特殊项目导入字典");
  113. }
  114. List<DictDataVo> dataVoList = dict.getDataVoList();
  115. if (CollectionUtils.isEmpty(dataVoList)) {
  116. throw new CostException("未找到特殊项目导入字典");
  117. }
  118. Map<String, String> dictionaryCodeNameMap = dataVoList.stream().collect(Collectors.toMap(DictDataVo::getCode, DictDataVo::getName, (a, b) -> b));
  119. List<CommonTitleVo> list = new ArrayList<>();
  120. if (!CollectionUtils.isEmpty(dictionaryCodeNameMap)) {
  121. list = dictionaryCodeNameMap.keySet().stream().map(s -> new CommonTitleVo(s, dictionaryCodeNameMap.get(s))).collect(Collectors.toList());
  122. }
  123. return list;
  124. }
  125. /**
  126. * 导入数据
  127. *
  128. * @param computeDate 核算年月
  129. * @param tableName 表名
  130. * @param file 导入文件
  131. */
  132. @Override
  133. @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
  134. public void importData(String computeDate, String tableName, MultipartFile file) {
  135. //excel 数据导入
  136. String fileName = file.getOriginalFilename();
  137. //导入文件上传
  138. String uploadFileUrl = uploadFile(file, fileName);
  139. //导入记录添加
  140. KpiComputeImport kpiComputeImport = new KpiComputeImport();
  141. kpiComputeImport.setComputeDate(computeDate);
  142. kpiComputeImport.setImportStatus(NumberConstant.ZERO);
  143. kpiComputeImport.setCreateTime(new Date());
  144. kpiComputeImport.setCreateUser(String.valueOf(UserContext.getCurrentUser().getId()));
  145. kpiComputeImport.setUrl(uploadFileUrl);
  146. kpiComputeImport.setTableName(tableName);
  147. kpiComputeImport.setFileName(fileName);
  148. kpiComputeImport.setHospId(UserContext.getCurrentLoginHospId());
  149. kpiComputeImport.setDelFlag(NumberConstant.ZERO);
  150. repository.save(kpiComputeImport);
  151. insertExcelData(kpiComputeImport.getId(), tableName, file, fileName, computeDate);
  152. }
  153. private void insertExcelData(Integer id, String tableName, MultipartFile file, String fileName, String computeDate) {
  154. try {
  155. assert fileName != null;
  156. File file1 = new File(fileName);
  157. FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
  158. String excelSql = readExcelSql(file1, tableName, id);
  159. SqlRunner sqlRunner = new SqlRunner(getConnection());
  160. sqlRunner.insert(excelSql);
  161. //更新新增人和时间
  162. String updateSql = "update " + "`" + tableName + "`" + "set" +
  163. "`create_user` = '" + UserContext.getCurrentUser().getId() + "' , `create_time` = '" + DateUtils.formatDate2String(new Date()) +
  164. "' where `compute_date` = '" + computeDate + "' and `hosp_id` = " + UserContext.getCurrentLoginHospId() +
  165. ";";
  166. sqlRunner.run(updateSql);
  167. } catch (IOException | SQLException | ClassNotFoundException e) {
  168. throw new RuntimeException(e);
  169. }
  170. }
  171. private String uploadFile(MultipartFile file, String fileName) {
  172. DateTime date = DateUtil.date();
  173. int month = DateUtil.month(date) + 1;
  174. int year = DateUtil.year(date);
  175. int day = DateUtil.dayOfMonth(date);
  176. Long hospId = UserContext.getCurrentLoginHospId();
  177. String fileUrl = "";
  178. try {
  179. String format = DateUtil.format(date, DatePattern.PURE_DATETIME_PATTERN);
  180. String originalFilename = format + fileName;
  181. String dataDirectory = minioConfig.getBucketName();
  182. String uploadFileName = "upload" + "/" + hospId + "/" + year + "/" + month + "/" + day + "/" + originalFilename;
  183. InputStream inputStream = file.getInputStream();
  184. minioFileUtil.putObject(dataDirectory, uploadFileName, inputStream);
  185. fileUrl = minioFileUtil.getObjectUrl(dataDirectory, uploadFileName);
  186. } catch (IOException e) {
  187. throw new RuntimeException(e);
  188. }
  189. return fileUrl;
  190. }
  191. /**
  192. * 作废导入数据
  193. *
  194. * @param id 记录id
  195. */
  196. @Override
  197. @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
  198. public void removeImport(Integer id) {
  199. KpiComputeImport kpiComputeImport = repository.getById(id);
  200. if (Objects.nonNull(kpiComputeImport)) {
  201. //更新表信息
  202. // String computeDate = kpiComputeImport.getComputeDate();
  203. String tableName = kpiComputeImport.getTableName();
  204. Long hospId = kpiComputeImport.getHospId();
  205. // TODO: 2023/7/24 导入的数据可能不是这个月的,用记录id 进行删除,有问题再看
  206. StringBuilder delSql = new StringBuilder().append("update " + "`").append(tableName).append("`").append("set")
  207. .append("`del_flag` = 1 , `update_user` = '").append(UserContext.getCurrentUser().getId())
  208. .append("' , `update_time` = '").append(DateUtils.formatDate2String(new Date())).append("' where `hosp_id` = ").append(hospId)
  209. .append(" and `import_id` = ").append(id).append(";");
  210. try {
  211. log.info("执行的sql语句:" + delSql);
  212. SqlRunner sqlRunner = new SqlRunner(getConnection());
  213. sqlRunner.run(delSql.toString());
  214. } catch (ClassNotFoundException | SQLException e) {
  215. throw new RuntimeException("删除导入数据错误" + e);
  216. }
  217. //更新 记录表信息
  218. kpiComputeImport.setImportStatus(NumberConstant.ONE);
  219. kpiComputeImport.setUpdateUser(String.valueOf(UserContext.getCurrentUser().getId()));
  220. kpiComputeImport.setUpdateTime(new Date());
  221. repository.updateById(kpiComputeImport);
  222. }
  223. }
  224. @Override
  225. @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
  226. public List<SheetImportResultVO> importMultipleSheets(String computeDate, MultipartFile file) {
  227. String fileName = file.getOriginalFilename();
  228. String uploadFileUrl = uploadFile(file, fileName);
  229. List<SheetImportResultVO> sheetResults = new ArrayList<>();
  230. try {
  231. File tempFile = File.createTempFile("excel-", ".tmp");
  232. file.transferTo(tempFile);
  233. List<CommonTitleVo> tableList = (List<CommonTitleVo>) getTableList();
  234. try (Workbook workbook = WorkbookFactory.create(tempFile)) {
  235. for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
  236. Sheet sheet = workbook.getSheetAt(i);
  237. String sheetName = sheet.getSheetName();
  238. SheetImportResultVO resultItem = new SheetImportResultVO();
  239. resultItem.setSheetName(sheetName);
  240. resultItem.setSheetIndex(i);
  241. Optional<CommonTitleVo> mapping = tableList.stream()
  242. .filter(t -> t.getName().equals(sheetName))
  243. .findFirst();
  244. if (!mapping.isPresent()) {
  245. log.warn("未找到sheet页 '{}' 对应的数据表配置,跳过导入", sheetName);
  246. resultItem.setSuccess(false);
  247. resultItem.setErrorMessage("未找到对应的数据库表配置");
  248. sheetResults.add(resultItem);
  249. continue;
  250. }
  251. String tableName = mapping.get().getCode();
  252. resultItem.setTableName(tableName);
  253. try {
  254. KpiComputeImport kpiComputeImport = new KpiComputeImport();
  255. kpiComputeImport.setComputeDate(computeDate);
  256. kpiComputeImport.setImportStatus(NumberConstant.ZERO);
  257. kpiComputeImport.setCreateTime(new Date());
  258. kpiComputeImport.setCreateUser(String.valueOf(UserContext.getCurrentUser().getId()));
  259. kpiComputeImport.setUrl(uploadFileUrl);
  260. kpiComputeImport.setTableName(tableName);
  261. kpiComputeImport.setFileName(String.format("%s_%s", fileName, sheetName));
  262. kpiComputeImport.setHospId(UserContext.getCurrentLoginHospId());
  263. kpiComputeImport.setDelFlag(NumberConstant.ZERO);
  264. repository.save(kpiComputeImport);
  265. insertExcelDataForSheet(kpiComputeImport.getId(), tableName, file, fileName, computeDate, sheet);
  266. resultItem.setSuccess(true);
  267. resultItem.setImportId(kpiComputeImport.getId());
  268. resultItem.setImportTime(kpiComputeImport.getCreateTime());
  269. } catch (Exception e) {
  270. log.error("导入sheet页 '{}' 出错: {}", sheetName, e.getMessage(), e);
  271. resultItem.setSuccess(false);
  272. resultItem.setErrorMessage("导入失败: " + e.getMessage());
  273. }
  274. sheetResults.add(resultItem);
  275. }
  276. }
  277. // 删除临时文件
  278. tempFile.delete();
  279. } catch (Exception e) {
  280. throw new RuntimeException("导入发生异常", e);
  281. }
  282. return sheetResults;
  283. }
  284. @SneakyThrows
  285. private void insertExcelDataForSheet(Integer id, String tableName, MultipartFile file, String fileName, String computeDate, Sheet sheet) {
  286. try {
  287. // 将MultipartFile转换为InputStream
  288. InputStream inputStream = file.getInputStream();
  289. // 这里假设有一个方法可以从给定的InputStream和sheet对象中读取SQL语句
  290. String excelSql = readExcelSqlFromSheet(inputStream, sheet, tableName, id);
  291. // 执行SQL插入操作
  292. SqlRunner sqlRunner = new SqlRunner(getConnection());
  293. sqlRunner.insert(excelSql);
  294. // 更新新增人和时间
  295. String updateSql = "UPDATE `" + tableName + "` SET " +
  296. "`create_user` = '" + UserContext.getCurrentUser().getId() + "', " +
  297. "`create_time` = '" + DateUtils.formatDate2String(new Date()) + "' " +
  298. "WHERE `compute_date` = '" + computeDate + "' AND `hosp_id` = " + UserContext.getCurrentLoginHospId() + ";";
  299. sqlRunner.run(updateSql);
  300. } catch (IOException | SQLException e) {
  301. // 记录日志而不是抛出异常,以避免中断其他sheet页的处理
  302. log.error("Error inserting data for sheet: {}", sheet.getSheetName(), e);
  303. }
  304. }
  305. private String readExcelSqlFromSheet(InputStream inputStream, Sheet sheet, String tableName, Integer id) throws IOException {
  306. StringBuilder sqlBuilder = new StringBuilder();
  307. boolean firstRow = true;
  308. Row headerRow = null;
  309. DataFormatter dataFormatter = new DataFormatter();
  310. int rowCount = 0;
  311. for (Row row : sheet) {
  312. // 第一行作为标题行
  313. if (rowCount == 0) {
  314. headerRow = row;
  315. rowCount++;
  316. continue;
  317. }
  318. if (rowCount == 1) {
  319. // 第二行为说明行,跳过
  320. rowCount++;
  321. continue;
  322. }
  323. sqlBuilder.append("INSERT INTO `").append(tableName).append("` (");
  324. // 构建字段名部分
  325. for (int i = 0; i < headerRow.getLastCellNum(); i++) {
  326. if (i > 0) {
  327. sqlBuilder.append(", ");
  328. }
  329. Cell headerCell = headerRow.getCell(i);
  330. sqlBuilder.append("`").append(headerCell.getStringCellValue()).append("`");
  331. }
  332. sqlBuilder.append(", `import_id`) VALUES (");
  333. // 构建值部分
  334. for (int i = 0; i < row.getLastCellNum(); i++) {
  335. if (i > 0) {
  336. sqlBuilder.append(", ");
  337. }
  338. Cell cell = row.getCell(i);
  339. if (cell == null) {
  340. sqlBuilder.append("NULL");
  341. continue;
  342. }
  343. switch (cell.getCellType()) {
  344. case STRING:
  345. sqlBuilder.append("'").append(cell.getStringCellValue()).append("'");
  346. break;
  347. case NUMERIC:
  348. String formattedValue = dataFormatter.formatCellValue(cell);
  349. // 判断是否是日期类型
  350. if (HSSFDateUtil.isCellDateFormatted(cell)) {
  351. sqlBuilder.append("'").append(cell.getDateCellValue()).append("'");
  352. } else {
  353. sqlBuilder.append(formattedValue);
  354. }
  355. break;
  356. case BOOLEAN:
  357. sqlBuilder.append(cell.getBooleanCellValue() ? 1 : 0);
  358. break;
  359. case FORMULA:
  360. sqlBuilder.append("'").append(cell.getCellFormula()).append("'");
  361. break;
  362. case BLANK:
  363. sqlBuilder.append("NULL");
  364. break;
  365. default:
  366. sqlBuilder.append("NULL");
  367. }
  368. }
  369. sqlBuilder.append(", ").append(id).append(");\n");
  370. rowCount++;
  371. }
  372. return sqlBuilder.toString();
  373. }
  374. /**
  375. * 复原导入数据
  376. *
  377. * @param id 记录id
  378. */
  379. @Override
  380. @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
  381. public void recoverImport(Integer id) {
  382. KpiComputeImport kpiComputeImport = repository.getById(id);
  383. if (Objects.nonNull(kpiComputeImport)) {
  384. //更新表信息
  385. String computeDate = kpiComputeImport.getComputeDate();
  386. String tableName = kpiComputeImport.getTableName();
  387. Long hospId = kpiComputeImport.getHospId();
  388. StringBuilder delSql = new StringBuilder().append("update " + "`").append(tableName).append("`").append("set")
  389. .append("`del_flag` = 0 , `update_user` = '").append(UserContext.getCurrentUser().getId())
  390. .append("' , `update_time` = '").append(DateUtils.formatDate2String(new Date())).append("' where `hosp_id` = ").append(hospId)
  391. .append(" and `import_id` = ").append(id).append(";");
  392. try {
  393. log.info("执行的sql语句:" + delSql);
  394. SqlRunner sqlRunner = new SqlRunner(getConnection());
  395. sqlRunner.run(delSql.toString());
  396. } catch (ClassNotFoundException | SQLException e) {
  397. throw new RuntimeException("复原数据错误" + e);
  398. }
  399. //更新 记录表信息
  400. kpiComputeImport.setImportStatus(NumberConstant.ZERO);
  401. kpiComputeImport.setUpdateUser(String.valueOf(UserContext.getCurrentUser().getId()));
  402. kpiComputeImport.setUpdateTime(new Date());
  403. repository.updateById(kpiComputeImport);
  404. }
  405. }
  406. public static String readExcelSql(File file, String tableName, Integer id) throws IOException {
  407. // 获取excel工作簿对象
  408. String sql = null;
  409. String fileName = file.getName();
  410. String substring = fileName.substring(fileName.lastIndexOf("."));
  411. if (".xls".equals(substring)) {
  412. HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));
  413. for (Sheet sheet : workbook) {
  414. List<String> headerList = new ArrayList<>();
  415. List<Map<String, Object>> dataList = new ArrayList<>();
  416. System.out.println(sheet.getSheetName());
  417. int i = 0;
  418. for (Row row : sheet) {
  419. if (i == 1) {
  420. i++;
  421. continue;
  422. }
  423. if (i == 0) {
  424. if (i == 0) {
  425. for (Cell cell : row) {
  426. headerList.add(cell.getStringCellValue());
  427. }
  428. // if(headerList.size() > 0) {
  429. // String createTableSql = createTable(headerList, sheetName);
  430. // System.out.println("生成的创建表语句:"+ createTableSql);
  431. // }
  432. }
  433. } else {
  434. Map<String, Object> map = new HashMap<>();
  435. int j = 0;
  436. for (Cell cell : row) {
  437. //设置单元格类型
  438. cell.setCellType(CellType.STRING);
  439. map.put(headerList.get(j), cell.getStringCellValue());
  440. j++;
  441. }
  442. dataList.add(map);
  443. }
  444. i++;
  445. }
  446. //组装记录表和hospId
  447. setCommonData(id, dataList);
  448. sql = insertFromMap(dataList, tableName);
  449. }
  450. } else if (".xlsx".equals(substring)) {
  451. XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file));
  452. for (Sheet sheet : workbook) {
  453. List<String> headerList = new ArrayList<>();
  454. List<Map<String, Object>> dataList = new ArrayList<>();
  455. System.out.println(sheet.getSheetName());
  456. String sheetName = sheet.getSheetName();
  457. int i = 0;
  458. for (Row row : sheet) {
  459. if (i == 1) {
  460. i++;
  461. continue;
  462. }
  463. if (i == 0) {
  464. if (i == 0) {
  465. for (Cell cell : row) {
  466. headerList.add(cell.getStringCellValue());
  467. }
  468. // if(headerList.size() > 0) {
  469. // String createTableSql = createTable(headerList, sheetName);
  470. // System.out.println("生成的创建表语句:"+ createTableSql);
  471. // }
  472. }
  473. } else {
  474. Map<String, Object> map = new HashMap<>();
  475. int j = 0;
  476. for (Cell cell : row) {
  477. //设置单元格类型
  478. cell.setCellType(CellType.STRING);
  479. map.put(headerList.get(j), cell.getStringCellValue());
  480. j++;
  481. }
  482. dataList.add(map);
  483. }
  484. i++;
  485. }
  486. setCommonData(id, dataList);
  487. sql = insertFromMap(dataList, tableName);
  488. }
  489. }
  490. return sql;
  491. }
  492. private static void setCommonData(Integer id, List<Map<String, Object>> dataList) {
  493. if (!CollectionUtils.isEmpty(dataList)) {
  494. dataList.forEach(stringObjectMap -> {
  495. stringObjectMap.put("hosp_id", UserContext.getCurrentLoginHospId());
  496. stringObjectMap.put("import_id", id);
  497. });
  498. }
  499. }
  500. /**
  501. * 生成创建表结构
  502. *
  503. * @param headerList 表头
  504. * @param sheetName sheet名
  505. * @return
  506. */
  507. public static String createTable(List<String> headerList, String sheetName) {
  508. StringBuffer createTableSql = new StringBuffer();
  509. if (headerList.size() > 0) {
  510. createTableSql.append("SET NAMES utf8mb4;\n");
  511. createTableSql.append("SET FOREIGN_KEY_CHECKS = 0;\n");
  512. createTableSql.append("DROP TABLE IF EXISTS `" + sheetName + "`;\n");
  513. createTableSql.append("CREATE TABLE `" + sheetName + "`");
  514. createTableSql.append("(\n");
  515. createTableSql.append("`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',\n");
  516. int k = 0;
  517. for (String key : headerList) {
  518. createTableSql.append("`" + key + "` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,\n");
  519. k++;
  520. if (k == headerList.size()) {
  521. createTableSql.append("PRIMARY KEY (`id`) USING BTREE)\n");
  522. createTableSql.append("ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin COMMENT = '' ROW_FORMAT = Dynamic;\n");
  523. createTableSql.append("SET FOREIGN_KEY_CHECKS = 1;");
  524. }
  525. }
  526. }
  527. return createTableSql.toString();
  528. }
  529. /**
  530. * map对象生成insert插入语句
  531. *
  532. * @param dataList
  533. * @param tableName
  534. */
  535. public static String insertFromMap(List<Map<String, Object>> dataList, String tableName) {
  536. String sql = null;
  537. if (dataList.size() > 0) {
  538. int i = 0;
  539. StringBuilder strKey = new StringBuilder();
  540. //插入sql语句
  541. StringBuilder insertSql = new StringBuilder().append("INSERT INTO " + "`").append(tableName).append("`");
  542. StringBuilder value = new StringBuilder();
  543. for (Map<String, Object> map : dataList) {
  544. //存入key的字符串数组
  545. //存入value的字符串数组
  546. ArrayList<Object> arrValue = new ArrayList<>();
  547. //拼接sql
  548. ArrayList<Object> arrKey = new ArrayList<>(map.keySet());
  549. for (String keys : map.keySet()) {
  550. arrValue.add(map.get(keys));
  551. }
  552. if (i == 0) {
  553. //遍历存的key字符串数组拼接sql
  554. for (int j = 0; j < arrKey.size(); j++) {
  555. strKey.append("`").append(arrKey.get(j)).append("`");
  556. if (j != arrKey.size() - 1) {//拼上","最后一个不拼
  557. strKey.append(",");
  558. }
  559. }
  560. }
  561. i++;
  562. StringBuilder strVal = new StringBuilder();
  563. //遍历存的value字符串数组拼接sql
  564. for (int j = 0; j < arrValue.size(); j++) {
  565. if (null != arrValue.get(j) && !"".equals(arrValue.get(j))) {
  566. strVal.append("'").append(arrValue.get(j)).append("'");//拼接单引号
  567. } else if ("".equals(arrValue.get(j))) {
  568. strVal.append((String) null);
  569. } else {
  570. strVal.append(arrValue.get(j));
  571. }
  572. if (j != arrValue.size() - 1) {//拼上","最后一个不拼
  573. strVal.append(",");
  574. }
  575. }
  576. String stringEntryVal = strVal.toString();
  577. value.append("(").append(stringEntryVal).append(")");
  578. if (i < dataList.size()) {
  579. value.append(",");
  580. }
  581. }
  582. insertSql.append("(").append(strKey).append(")");
  583. insertSql.append(" VALUES ");
  584. insertSql.append(value).append(";");
  585. System.out.println("生成插入数据sql:" + insertSql.toString());
  586. sql = insertSql.toString();
  587. }
  588. return sql;
  589. }
  590. private Connection getConnection() throws ClassNotFoundException, SQLException {
  591. Class.forName(driver);
  592. return DriverManager.getConnection(url, username, password);
  593. }
  594. }