python 将excel 导入 mysql
时间: 2024-06-19 11:02:28 浏览: 14
Python可以通过pandas和MySQLdb模块将Excel导入MySQL,具体步骤如下:
1. 安装pandas和MySQLdb模块:
```python
pip install pandas
pip install MySQL-python
```
2. 使用pandas读取Excel文件:
```python
import pandas as pd
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')
```
3. 连接MySQL数据库:
```python
import MySQLdb
conn = MySQLdb.connect(host='localhost', port=3306, user='root', passwd='password', db='test')
```
4. 将数据导入MySQL数据库:
```python
cursor = conn.cursor()
for i,row in df.iterrows():
sql = "INSERT INTO test_table (col1, col2, col3) VALUES (%s, %s, %s)"
cursor.execute(sql, tuple(row))
conn.commit()
cursor.close()
conn.close()
```
其中,'data.xlsx'是Excel文件名,'Sheet1'是Excel中的工作表名,'test'是MySQL数据库名,'test_table'是表名,'col1'、'col2'、'col3'是表中的列名。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)