python写入excel嵌套字典文件
时间: 2023-10-18 09:25:04 浏览: 282
python将数据写入excel
5星 · 资源好评率100%
可以使用Python中的`openpyxl`库来实现将嵌套字典写入Excel文件的功能。具体步骤如下:
1. 安装`openpyxl`库:在命令行中输入`pip install openpyxl`进行安装。
2. 导入`openpyxl`库:在Python脚本中导入`openpyxl`库,代码如下:
```python
from openpyxl import Workbook
```
3. 创建Excel文件并新建一个工作表:使用`openpyxl`库创建一个Excel文件,并新建一个工作表,代码如下:
```python
workbook = Workbook()
sheet = workbook.active
```
4. 将嵌套字典的键作为Excel文件的列名写入工作表:使用`sheet.append()`方法将嵌套字典的键作为Excel文件的列名写入工作表,代码如下:
```python
data = {
"A": {"name": "Alice", "age": 25},
"B": {"name": "Bob", "age": 30},
"C": {"name": "Charlie", "age": 35}
}
first_row = ["ID", "Name", "Age"]
sheet.append(first_row)
```
5. 将嵌套字典的值写入工作表:使用`sheet.append()`方法将嵌套字典的值写入工作表,代码如下:
```python
for key, value in data.items():
row = [key, value["name"], value["age"]]
sheet.append(row)
```
6. 保存Excel文件:使用`workbook.save()`方法保存Excel文件,代码如下:
```python
workbook.save("data.xlsx")
```
完整代码如下:
```python
from openpyxl import Workbook
workbook = Workbook()
sheet = workbook.active
data = {
"A": {"name": "Alice", "age": 25},
"B": {"name": "Bob", "age": 30},
"C": {"name": "Charlie", "age": 35}
}
first_row = ["ID", "Name", "Age"]
sheet.append(first_row)
for key, value in data.items():
row = [key, value["name"], value["age"]]
sheet.append(row)
workbook.save("data.xlsx")
```
阅读全文