python 使用openpyxl将数据:[{"name":"li","age":18},{"name":"wang","age":24}] 写道Excel文件中 字典key为表头,表头字体为粗体
时间: 2023-08-14 18:04:49 浏览: 98
使用Python工具包Openpyxl进行Excel处理
要使用openpyxl将数据写入Excel文件中,并设置表头字体为粗体,可以按照以下步骤进行操作:
1. 首先,导入openpyxl库:
```python
import openpyxl
```
2. 创建一个新的Excel文件:
```python
workbook = openpyxl.Workbook()
```
3. 选择要操作的工作表:
```python
sheet = workbook.active
```
4. 定义要写入的数据:
```python
data = \[{"name":"li","age":18},{"name":"wang","age":24}\]
```
5. 写入表头,并设置字体为粗体:
```python
header = list(data\[0\].keys())
for col_num, header_title in enumerate(header, 1):
cell = sheet.cell(row=1, column=col_num)
cell.value = header_title
cell.font = openpyxl.styles.Font(bold=True)
```
6. 写入数据:
```python
for row_num, row_data in enumerate(data, 2):
for col_num, col_data in enumerate(row_data.values(), 1):
cell = sheet.cell(row=row_num, column=col_num)
cell.value = col_data
```
7. 保存Excel文件:
```python
workbook.save("output.xlsx")
```
这样,数据就会被写入Excel文件中,并且表头的字体会被设置为粗体。你可以将文件名修改为你想要的名称。
#### 引用[.reference_title]
- *1* *2* [010 python数据结构与算法:算法概论;时间复杂度](https://blog.csdn.net/qq_34539676/article/details/106865325)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [python编程入门之二:必备基础知识](https://blog.csdn.net/weixin_35503004/article/details/113987334)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文