當我們需要將Excel表中的數據導入MySQL時,我們可以使用Java開發工具IDEA來實現這個過程
首先,我們需要在項目中添加相關的依賴,如:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.19</version> </dependency>
然后,我們需要創建一個ExcelUtil工具類,用來讀取Excel表中的數據:
public class ExcelUtil { public static List<List<String>> readExcel(String path) { List<List<String>> result = new ArrayList<>(); try { Workbook workbook = WorkbookFactory.create(new File(path)); Sheet sheet = workbook.getSheetAt(0); for (int i = 0; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); List<String> rowList = new ArrayList<>(); for (int j = 0; j < row.getLastCellNum(); j++) { Cell cell = row.getCell(j); String value = ""; if (cell != null) { value = cell.toString(); } rowList.add(value); } result.add(rowList); } } catch (Exception e) { e.printStackTrace(); } return result; } }
接著,我們需要創建一個MysqlUtil工具類,用來將數據導入MySQL中:
public class MysqlUtil { public static void insertData(List<List<String>> data) { try { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC"; String user = "root"; String password = "123456"; Connection connection = DriverManager.getConnection(url, user, password); Statement statement = connection.createStatement(); for (List<String> row : data) { String sql = "INSERT INTO student(name, age, sex) VALUES('" + row.get(0) + "', " + row.get(1) + ", '" + row.get(2) + "')"; statement.executeUpdate(sql); } statement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } } }
最后,在Main方法中調用ExcelUtil和MysqlUtil的方法即可:
public static void main(String[] args) { List<List<String>> data = ExcelUtil.readExcel("students.xlsx"); MysqlUtil.insertData(data); }
這樣,我們就可以通過IDEA將Excel表中的數據導入MySQL中了。