c#导入excel到mysql
时间: 2023-10-11 19:26:47 浏览: 65
你可以使用以下步骤将 Excel 文件中的数据导入到 MySQL 数据库中:
1. 安装 MySQL Connector/NET,这是一个 ADO.NET 驱动程序,允许你通过 .NET 应用程序访问 MySQL 数据库。
2. 在 C# 代码中,使用 `OleDbConnection` 对象创建一个连接到 Excel 文件。
```csharp
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=path\\to\\excel\\file.xlsx;Extended Properties='Excel 12.0;HDR=YES;IMEX=1;'";
OleDbConnection connection = new OleDbConnection(connectionString);
```
3. 使用 `OleDbDataAdapter` 对象从 Excel 文件中获取数据。
```csharp
string query = "SELECT * FROM [Sheet1$]";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, connection);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
```
4. 创建一个 MySQL 数据库连接并插入数据。
```csharp
MySqlConnection mysqlConnection = new MySqlConnection("SERVER=localhost;DATABASE=mydatabase;UID=myusername;PASSWORD=mypassword;");
mysqlConnection.Open();
foreach (DataRow row in dataTable.Rows)
{
MySqlCommand command = new MySqlCommand("INSERT INTO mytable (column1,column2,column3) VALUES (@column1,@column2,@column3)", mysqlConnection);
command.Parameters.AddWithValue("@column1", row["column1"].ToString());
command.Parameters.AddWithValue("@column2", row["column2"].ToString());
command.Parameters.AddWithValue("@column3", row["column3"].ToString());
command.ExecuteNonQuery();
}
mysqlConnection.Close();
```
请注意,这只是一个简单的示例代码。在实际应用中,你需要根据自己的需求进行适当的修改和优化。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)