POI(Apache POI)是一个开源的Java API,用于处理Microsoft Office文档,包括Excel文件。通过POI,可以读取、写入和修改Excel文件中的数据。MySQL是一种关系型数据库管理系统,广泛用于存储和管理结构化数据。
以下是一个使用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();
}
} catch (IOException | SQLException e) {
e.printStackTrace();
}
}
}
NullPointerException
或IOException
。SQLException
。领取专属 10元无门槛券
手把手带您无忧上云