用python同一条件筛选多张工作表的列并保存
时间: 2023-09-15 18:21:04 浏览: 60
你可以使用 `pandas` 库来筛选多张工作表的列。以下是一个示例代码:
```python
import pandas as pd
# 定义筛选条件
conditions = {
'Sheet1': ['col1', 'col2'],
'Sheet2': ['col3', 'col4'],
'Sheet3': ['col5', 'col6']
}
# 读取 Excel 文件
excel_file = pd.read_excel('your_excel_file.xlsx', sheet_name=list(conditions.keys()))
# 筛选列并保存到新的 Excel 文件
writer = pd.ExcelWriter('new_excel_file.xlsx')
for sheet_name in excel_file.keys():
sheet_data = excel_file[sheet_name][conditions[sheet_name]]
sheet_data.to_excel(writer, sheet_name=sheet_name)
writer.save()
```
在上面的代码中,首先定义了一个字典 `conditions`,其中包含了每个工作表需要筛选的列。然后使用 `pandas` 的 `read_excel` 函数读取 Excel 文件,并指定要读取的工作表名字。接着,遍历每个工作表,根据 `conditions` 中的筛选条件筛选出对应的列,最后使用 `to_excel` 方法将结果保存到新的 Excel 文件中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)