用java 写一个execl导入
时间: 2023-05-12 13:03:29 浏览: 90
基于Java的execl导入例子
非常感谢您的提问!以下是一个简单的 Java 代码示例,可以用于将 Excel 文件导入到数据库中:
```
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelImporter {
public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
String username = "myusername";
String password = "mypassword";
String excelFilePath = "path/to/excel/file.xlsx";
String tableName = "mytable";
try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) {
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
String sql = "INSERT INTO " + tableName + " (column1, column2, column3) VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
int batchSize = 20;
int count = 0;
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Cell cell1 = row.getCell(0);
Cell cell2 = row.getCell(1);
Cell cell3 = row.getCell(2);
statement.setString(1, cell1.getStringCellValue());
statement.setString(2, cell2.getStringCellValue());
statement.setString(3, cell3.getStringCellValue());
statement.addBatch();
if (++count % batchSize == 0) {
statement.executeBatch();
}
}
statement.executeBatch();
workbook.close();
inputStream.close();
System.out.println("Data imported successfully!");
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
}
```
请注意,这只是一个简单的示例,您需要根据您的具体需求进行修改和调整。同时,您需要确保您已经正确地安装了 MySQL 数据库和相关的 JDBC 驱动程序。
阅读全文