需求

业务给到一份excel表格,需要导入到对应的数据表,由于字段不同以及对应到多张表,数据也不完整,
打算先临时导入到数据库临时表中,再用sql语句处理数据后再使用sql导入到对应的表。

pom依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>easyexcel</artifactId>
  5. <version>2.2.10</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>mysql</groupId>
  9. <artifactId>mysql-connector-java</artifactId>
  10. <version>5.1.32</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.projectlombok</groupId>
  14. <artifactId>lombok</artifactId>
  15. <version>1.18.12</version>
  16. </dependency>
  17. </dependencies>

导入代码

  1. public static void main(String[] args) {
  2. Connection conn = null;
  3. Statement stmt = null;
  4. try {
  5. Class.forName(JDBC_DRIVER);
  6. System.out.println("连接数据库...");
  7. conn = DriverManager.getConnection(DB_URL, USER, PASS);
  8. String fileName = "F:\\test\\data.xlsx";
  9. List<Map<String, String>> list = EasyExcel.read(fileName).sheet().doReadSync();
  10. for (Map<String, String> row : list) {
  11. Set<Map.Entry<String, String>> entries = row.entrySet();
  12. StringBuilder values = new StringBuilder("(");
  13. for (Map.Entry<String, String> entry : entries) {
  14. String v = entry.getValue();
  15. if (v == null) {
  16. values.append("null,");
  17. continue;
  18. }
  19. v = v.replaceAll("'", "\\\\'");
  20. values.append("'").append(v).append("',");
  21. }
  22. values = new StringBuilder(values.substring(0, values.length() - 1));
  23. values.append(")");
  24. stmt = conn.createStatement();
  25. String sql = "INSERT INTO ex(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20," +
  26. "a21,a22)" +
  27. " VALUES" + values;
  28. System.out.println(sql);
  29. stmt = conn.createStatement();
  30. stmt.executeUpdate(sql);
  31. stmt.close();
  32. // conn.close();
  33. }
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. } finally {
  37. // 关闭资源
  38. if (stmt != null) {
  39. try {
  40. stmt.close();
  41. } catch (SQLException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. try {
  46. if (conn != null) {
  47. conn.close();
  48. }
  49. } catch (SQLException se) {
  50. se.printStackTrace();
  51. }
  52. }
  53. }