python用pandas读取一个文件夹内所有的excel文件,合并后生成一个新的表格并设置表格属性
时间: 2023-12-20 20:03:54 浏览: 198
可以使用Python的pandas和os库,以及openpyxl库来读取一个文件夹内所有的Excel文件,合并后生成一个新的表格,并设置表格属性。
以下是一个示例代码:
```python
import pandas as pd
import os
from openpyxl.styles import Font, Color, PatternFill
# 读取所有Excel文件
path = 'folder_path'
all_files = os.listdir(path)
excel_files = [f for f in all_files if f.endswith('.xlsx')]
# 合并数据
merged_df = pd.DataFrame()
for file in excel_files:
df = pd.read_excel(os.path.join(path, file))
merged_df = merged_df.append(df, ignore_index=True)
# 创建Excel文件
writer = pd.ExcelWriter('new_table.xlsx', engine='openpyxl')
# 将数据写入Excel文件并设置单元格格式
merged_df.to_excel(writer, index=False, sheet_name='Sheet1')
# 获取工作表对象
worksheet = writer.sheets['Sheet1']
# 设置单元格格式
header_font = Font(bold=True, color='FFFFFF')
header_fill = PatternFill(fgColor='000000', fill_type='solid')
for cell in worksheet['A1:Z1']:
for header in cell:
header.font = header_font
header.fill = header_fill
# 保存文件
writer.save()
```
这个示例代码将读取指定文件夹内所有的Excel文件,并将它们合并为一个DataFrame对象。然后,将合并的数据保存为一个名为new_table.xlsx的Excel文件,并将第一行的单元格设置为加粗字体和黑色背景色。你可以根据需要修改单元格属性。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044736.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)