Java 导入 Excel 到 MySQL 涉及以下几个基础概念:
.xls
和 .xlsx
,分别对应旧版和新版的 Excel 文件。以下是一个简单的示例代码,展示如何使用 Java 和 Apache POI 将 Excel 文件中的数据导入到 MySQL 数据库中:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ExcelToMySQL {
public static void main(String[] args) {
String excelFilePath = "path/to/your/excel/file.xlsx";
String jdbcUrl = "jdbc:mysql://localhost:3306/your_database";
String username = "your_username";
String password = "your_password";
try (FileInputStream fileInputStream = new FileInputStream(excelFilePath);
Workbook workbook = new XSSFWorkbook(fileInputStream);
Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) {
Sheet sheet = workbook.getSheetAt(0);
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO your_table (column1, column2) VALUES (?, ?)");
for (Row row : sheet) {
Cell cell1 = row.getCell(0);
Cell cell2 = row.getCell(1);
String value1 = cell1.getStringCellValue();
String value2 = cell2.getStringCellValue();
preparedStatement.setString(1, value1);
preparedStatement.setString(2, value2);
preparedStatement.executeUpdate();
}
System.out.println("Data imported successfully!");
} catch (IOException | SQLException e) {
e.printStackTrace();
}
}
}
通过以上步骤和示例代码,你可以实现将 Excel 文件中的数据导入到 MySQL 数据库中。如果遇到具体问题,可以根据错误信息进行排查和解决。
领取专属 10元无门槛券
手把手带您无忧上云