当前位置:   article > 正文

java获取excel数据导入数据库_java读取excel文件并导入数据库

java读取excel文件并导入数据库

Excel的工具类,BuiPatientInfo是自己定义的接收数据的实体类

ExcelUtils源自通过java将Excel表格导入数据到数据库_java导入excel数据到数据库-CSDN博客

  1. package com.example.demo.utils;
  2. import com.example.demo.utils.BuiPatientInfo;
  3. import com.spire.ms.System.DateTime;
  4. import org.apache.poi.hssf.usermodel.HSSFCell;
  5. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  6. import org.apache.poi.ss.usermodel.*;
  7. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  8. import org.springframework.web.multipart.MultipartFile;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. import java.text.DecimalFormat;
  12. import java.text.SimpleDateFormat;
  13. import java.time.LocalDate;
  14. import java.time.LocalDateTime;
  15. import java.time.format.DateTimeFormatter;
  16. import java.util.ArrayList;
  17. import java.util.Date;
  18. import java.util.List;
  19. import java.util.Locale;
  20. /**
  21. * @author xjt
  22. * @version 1.0
  23. */
  24. public class ExcelUtils {
  25. //总行数
  26. private static int totalRows = 0;
  27. //总条数
  28. private static int totalCells = 0;
  29. //错误信息接收器
  30. private static String errorMsg;
  31. /**
  32. * 读EXCEL文件,获取信息集合
  33. * @return
  34. */
  35. public static List<BuiPatientInfo> getExcelInfo(MultipartFile mFile) {
  36. String fileName = mFile.getOriginalFilename();//获取文件名
  37. try {
  38. if (!validateExcel(fileName)) {// 验证文件名是否合格
  39. return null;
  40. }
  41. boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
  42. if (isExcel2007(fileName)) {
  43. isExcel2003 = false;
  44. }
  45. List<BuiPatientInfo> userList = createExcel(mFile.getInputStream(), isExcel2003);
  46. return userList;
  47. } catch (Exception e) {
  48. e.printStackTrace();
  49. }
  50. return null;
  51. }
  52. /**
  53. * 根据excel里面的内容读取客户信息
  54. * @param is 输入流
  55. * @param isExcel2003 excel是2003还是2007版本
  56. * @return
  57. * @throws IOException
  58. */
  59. public static List<BuiPatientInfo> createExcel(InputStream is, boolean isExcel2003) {
  60. try{
  61. Workbook wb = null;
  62. if (isExcel2003) {// 当excel是2003时,创建excel2003
  63. wb = new HSSFWorkbook(is);
  64. } else {// 当excel是2007时,创建excel2007
  65. wb = new XSSFWorkbook(is);
  66. }
  67. List<BuiPatientInfo> userList = readExcelValue(wb);// 读取Excel里面客户的信息
  68. return userList;
  69. } catch (IOException e) {
  70. e.printStackTrace();
  71. }
  72. return null;
  73. }
  74. /**
  75. * 读取Excel里面客户的信息
  76. * @param wb
  77. * @return
  78. */
  79. private static List<BuiPatientInfo> readExcelValue(Workbook wb) {
  80. //默认会跳过第一行标题
  81. // 得到第一个shell
  82. Sheet sheet = wb.getSheetAt(0);
  83. // 得到Excel的行数
  84. totalRows = sheet.getPhysicalNumberOfRows();
  85. // 得到Excel的列数(前提是有行数)
  86. if (totalRows > 1 && sheet.getRow(0) != null) {
  87. totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
  88. }
  89. List<BuiPatientInfo> userList = new ArrayList<BuiPatientInfo>();
  90. // 循环Excel行数
  91. for (int r = 1; r < totalRows; r++) {
  92. Row row = sheet.getRow(r);
  93. if (row == null){
  94. continue;
  95. }
  96. BuiPatientInfo user = new BuiPatientInfo();
  97. // 循环Excel的列
  98. for (int c = 0; c < totalCells; c++) {
  99. Cell cell = row.getCell(c);
  100. if (null != cell) {
  101. if (c == 0) { //第一列
  102. //如果是纯数字,将单元格类型转为String
  103. if(cell.getCellTypeEnum() == CellType.NUMERIC){
  104. cell.setCellType(CellType.STRING);
  105. }
  106. user.setIdentificationCode(cell.getStringCellValue());//将单元格数据赋值给user
  107. }
  108. else if (c == 1){
  109. if(cell.getCellTypeEnum() == CellType.NUMERIC){
  110. cell.setCellType(CellType.STRING);
  111. }
  112. Date javaDate = DateUtil.getJavaDate(Double.parseDouble(cell.getStringCellValue()));
  113. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  114. String formattedDate = formatter.format(javaDate);
  115. // DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
  116. // LocalDateTime dateTime = LocalDateTime.parse(input, inputFormatter);
  117. //
  118. // DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  119. // String formattedDateTime = dateTime.format(outputFormatter);
  120. user.setMoitorTime(formattedDate);
  121. }
  122. else if (c == 2){
  123. if(cell.getCellTypeEnum() == CellType.NUMERIC){
  124. cell.setCellType(CellType.STRING);
  125. }
  126. String stringCellValue = cell.getStringCellValue();
  127. user.setMoitorParam5(stringCellValue);
  128. }
  129. else if (c == 3){
  130. if(cell.getCellTypeEnum() == CellType.NUMERIC){
  131. cell.setCellType(CellType.STRING);
  132. }
  133. user.setMoitorParam1(String.valueOf(cell.getStringCellValue()));
  134. }
  135. else if (c == 4){
  136. if(cell.getCellTypeEnum() == CellType.NUMERIC){
  137. cell.setCellType(CellType.STRING);
  138. }
  139. user.setMoitorParam2(String.valueOf(cell.getStringCellValue()));
  140. }
  141. // else if (c == 5){
  142. // if(cell.getCellTypeEnum() == CellType.NUMERIC){
  143. // cell.setCellType(CellType.STRING);
  144. // }
  145. // user.setMoitorParam4(String.valueOf(cell.getStringCellValue()));
  146. // }
  147. // else if (c == 6){
  148. // if(cell.getCellTypeEnum() == CellType.NUMERIC){
  149. // cell.setCellType(CellType.STRING);
  150. // }
  151. // user.setMoitorParam5(String.valueOf(cell.getStringCellValue()));
  152. // }
  153. }
  154. }
  155. // 添加到list
  156. userList.add(user);
  157. }
  158. return userList;
  159. }
  160. /**
  161. * 验证EXCEL文件
  162. *
  163. * @param filePath
  164. * @return
  165. */
  166. public static boolean validateExcel(String filePath) {
  167. if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
  168. errorMsg = "文件名不是excel格式";
  169. return false;
  170. }
  171. return true;
  172. }
  173. // @描述:是否是2003的excel,返回true是2003
  174. public static boolean isExcel2003(String filePath) {
  175. return filePath.matches("^.+\\.(?i)(xls)$");
  176. }
  177. //@描述:是否是2007的excel,返回true是2007
  178. public static boolean isExcel2007(String filePath) {
  179. return filePath.matches("^.+\\.(?i)(xlsx)$");
  180. }
  181. }

写接口方法,由于mybatis传参一次只能传入65535个参数,所以数据多的时候分批导入,我这每次导入3000条。

  1. @Autowired
  2. private DemoMapper demoMapper;
  3. @PostMapping("/demo")
  4. public R demo(@RequestParam("file") MultipartFile file) {
  5. List<BuiPatientInfo> excelInfo = ExcelUtils.getExcelInfo(file);
  6. excelInfo.forEach(item -> {
  7. DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  8. LocalDateTime dateTime = LocalDateTime.parse(item.getMoitorTime(), inputFormatter);
  9. item.setMoitorTimee(dateTime);
  10. });
  11. int size = excelInfo.size();
  12. int i = size / 3000;
  13. int temp = size % 3000;
  14. int a = 1;
  15. if (temp == 0) {
  16. i--;
  17. }
  18. for (int k = 0; k <=i; k++) {
  19. if (k == i) {
  20. if (temp == 0) {
  21. temp = 3000;
  22. }
  23. List<BuiPatientInfo> subList = excelInfo.subList(k * 3000, (temp + k * 3000));
  24. System.out.println(k*3000);
  25. System.out.println(temp+k*3000);
  26. demoMapper.insertAll2(subList);
  27. } else {
  28. System.out.println(3000 * k);
  29. System.out.println(3000 * (k + 1));
  30. List<BuiPatientInfo> subList = excelInfo.subList(3000 * k, 3000 * (k + 1));
  31. demoMapper.insertAll2(subList);
  32. }
  33. }
  34. return R.success("成功");
  35. }

Mapper代码

  1. <insert id="insertAll2">
  2. <!-- <foreach collection="excelInfo" close="" separator="" open="" item="item" index="">-->
  3. <!-- insert into 表(id, device_id, device_code, device_type, monitor_param, monitor_data,-->
  4. <!-- monitor_unit, monitor_time)-->
  5. <!-- values ((select max(id) + 1 from 表),-->
  6. <!-- (select id from 表where identification_code = #{item.identificationCode}),-->
  7. <!-- #{item.identificationCode}, '3','水位',#{item.moitorParam2},'m',#{item.moitorTimee});-->
  8. <!-- insert into 表(id, device_id, device_code, device_type, monitor_param, monitor_data,-->
  9. <!-- monitor_unit, monitor_time)-->
  10. <!-- values ((select max(id) + 1 from drg_iot_equipment_data),-->
  11. <!-- (select id from 表where identification_code = #{item.identificationCode}),-->
  12. <!-- #{item.identificationCode}, '3','电压',#{item.moitorParam1},'V',#{item.moitorTimee});-->
  13. <!-- </foreach>-->
  14. </insert>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/726001
推荐阅读
相关标签
  

闽ICP备14008679号