使用python,选择文件夹,将文件夹内所有个excel合并至一个新excel中并保存在桌面
时间: 2023-05-15 07:06:35 浏览: 118
您可以使用Python中的pandas库来完成这个任务。以下是代码示例:
```python
import os
import pandas as pd
# 选择文件夹
folder_path = input("请输入文件夹路径:")
# 获取文件夹内所有excel文件的路径
file_paths = [os.path.join(folder_path, file) for file in os.listdir(folder_path) if file.endswith('.xlsx')]
# 读取所有excel文件并合并
df_list = []
for file_path in file_paths:
df = pd.read_excel(file_path)
df_list.append(df)
merged_df = pd.concat(df_list)
# 保存合并后的excel文件至桌面
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
merged_df.to_excel(os.path.join(desktop_path, "merged.xlsx"), index=False)
```
请注意,您需要安装pandas库才能运行此代码。您可以使用以下命令在命令行中安装pandas:
```
pip install pandas
```
相关问题
使用python,选择文件夹,将文件夹内所有个工作簿内的所有工作表合并至一个新工作簿中,并将新工作簿保存至桌面
你可以使用Python中的pandas库来完成这个任务。以下是代码示例:
```python
import os
import pandas as pd
# 选择文件夹
folder_path = input("请输入文件夹路径:")
# 遍历文件夹内所有Excel文件
excel_files = []
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith(".xlsx") or file.endswith(".xls"):
excel_files.append(os.path.join(root, file))
# 合并所有工作表
all_data = pd.DataFrame()
for file in excel_files:
excel_data = pd.read_excel(file, sheet_name=None)
for sheet_name, sheet_data in excel_data.items():
all_data = all_data.append(sheet_data)
# 保存至桌面
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
save_path = os.path.join(desktop_path, "merged.xlsx")
all_data.to_excel(save_path, index=False)
print("合并完成,文件保存至桌面!")
```
你可以将以上代码复制到Python文件中运行,然后输入文件夹路径即可完成合并。
使用python,选择文件夹,将文件夹内所有个工作簿内的所有工作表复制至一个新工作簿中,并保存至桌面
你可以使用Python中的pandas和openpyxl库来完成这个任务。以下是代码示例:
```python
import os
import pandas as pd
from openpyxl import Workbook
# 选择文件夹路径
folder_path = input("请输入文件夹路径:")
# 获取文件夹内所有Excel文件的路径
file_paths = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith('.xlsx')]
# 创建一个新的工作簿
new_workbook = Workbook()
# 遍历每个Excel文件,将所有工作表复制到新工作簿中
for file_path in file_paths:
# 读取Excel文件中的所有工作表
sheets = pd.read_excel(file_path, sheet_name=None)
for sheet_name, sheet_data in sheets.items():
# 将工作表数据添加到新工作簿中
new_workbook.create_sheet(sheet_name)
new_workbook[sheet_name].cell(row=1, column=1, value=file_path)
for r in sheet_data.values:
new_workbook[sheet_name].append(r)
# 将新工作簿保存到桌面
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
new_workbook.save(os.path.join(desktop_path, "merged_worksheets.xlsx"))
print("所有工作表已成功合并到一个新工作簿中,并保存至桌面!")
```
阅读全文
相关推荐
















