python中openyxl将字典写入excel
时间: 2023-06-20 18:08:20 浏览: 113
可以使用openpyxl将字典写入excel,具体步骤如下:
1. 导入openpyxl库
```python
import openpyxl
```
2. 创建一个新的工作簿,并选取一个工作表
```python
workbook = openpyxl.Workbook()
sheet = workbook.active
```
3. 定义一个字典,其中键是列名,值是数据
```python
data = {'姓名': ['张三', '李四', '王五'],
'年龄': [18, 20, 22],
'性别': ['男', '女', '男']}
```
4. 将列名写入第一行单元格
```python
for column, column_name in enumerate(data.keys()):
sheet.cell(row=1, column=column+1, value=column_name)
```
5. 将数据写入单元格
```python
for row, row_data in enumerate(zip(*data.values()), start=2):
for column, value in enumerate(row_data, start=1):
sheet.cell(row=row, column=column, value=value)
```
6. 保存工作簿
```python
workbook.save('data.xlsx')
```
完整代码如下:
```python
import openpyxl
workbook = openpyxl.Workbook()
sheet = workbook.active
data = {'姓名': ['张三', '李四', '王五'],
'年龄': [18, 20, 22],
'性别': ['男', '女', '男']}
for column, column_name in enumerate(data.keys()):
sheet.cell(row=1, column=column+1, value=column_name)
for row, row_data in enumerate(zip(*data.values()), start=2):
for column, value in enumerate(row_data, start=1):
sheet.cell(row=row, column=column, value=value)
workbook.save('data.xlsx')
```
阅读全文