pandas 设置表格的只把标题行填充为浅蓝色,全表加边框,并输出到EXCEL
时间: 2024-05-14 18:16:39 浏览: 21
中,应该怎么做?
可以按照以下代码实现:
```
import pandas as pd
# 读取数据
df = pd.read_excel('data.xlsx')
# 设置标题行为浅蓝色
header_fmt = {
'font_size': 14,
'bg_color': '#F0F8FF', # 浅蓝色
'align': 'center',
'valign': 'vcenter',
'bold': True,
'border': 1
}
header = [header_fmt] * len(df.columns)
df.style.apply(lambda x: header, axis=1, subset=pd.IndexSlice[:, :0])
# 加边框
fmt = {
'font_size': 12,
'border': 1
}
df.style.apply(lambda x: fmt, axis=None)
# 保存到Excel文件
writer = pd.ExcelWriter('output.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
for idx, col in enumerate(df):
worksheet.set_column(idx, idx, len(col) + 2)
writer.save()
```
运行该代码可以将表格中的标题行设置为浅蓝色,将全表加边框,并输出到Excel文件中。注意,需要安装pandas和xlsxwriter两个Python库。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)