java读取excel入库
时间: 2023-07-07 12:16:50 浏览: 99
java读取excel
Java可以使用Apache POI来读取Excel文件,然后将读取到的数据存入数据库中。下面是一个简单的示例代码:
```java
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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.xssf.usermodel.XSSFWorkbook;
public class ExcelToDB {
public static void main(String[] args) {
String jdbcURL = "jdbc:mysql://localhost:3306/mydb";
String username = "root";
String password = "password";
String excelFilePath = "data.xlsx";
try (Connection connection = DriverManager.getConnection(jdbcURL, username, password);
FileInputStream inputStream = new FileInputStream(excelFilePath);
Workbook workbook = new XSSFWorkbook(inputStream)) {
Sheet firstSheet = workbook.getSheetAt(0);
String insertQuery = "INSERT INTO mytable (name, age) VALUES (?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);
for (Row nextRow : firstSheet) {
Cell nameCell = nextRow.getCell(0);
Cell ageCell = nextRow.getCell(1);
String name = nameCell.getStringCellValue();
int age = (int) ageCell.getNumericCellValue();
preparedStatement.setString(1, name);
preparedStatement.setInt(2, age);
preparedStatement.executeUpdate();
}
System.out.println("Data imported successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这段代码将Excel文件中第一个Sheet的数据读取出来,然后插入到数据库表`mytable`中。你需要根据实际情况修改数据库连接信息、Excel文件路径、插入语句等。
阅读全文