import pandas as pd
import glob
# 查找当前目录及其子目录下所有以.txt结尾的文件
csv_files = glob.glob(r"D:\机械项目研报\机械项目研报*.xlsx", recursive=True)

# 创建一个空的DataFrame用于存储合并后的数据
merged_data = pd.DataFrame()

# 逐个读取CSV文件并合并到DataFrame中
for file in csv_files:
    data = pd.read_excel(file,dtype=str)
    # 去掉最后一列
    # data = data.iloc[:, :-1]
    dad=pd.DataFrame(data,dtype=str)
    merged_data = merged_data.append(dad, ignore_index=True)
sorted_df = merged_data.sort_values('industry')
grouped = merged_data.groupby('industry')
# 将合并后的数据保存到新的CSV文件中
# merged_data.to_csv(r"D:\hg\tmp\11.csv", encoding='gbk', index=False, quoting=1, quotechar='"', escapechar='\\')
# merged_data.to_excel(r"D:\机械项目研报\机械项目研报汇总.xlsx", index=False, engine='openpyxl')
with pd.ExcelWriter(r'D:\机械项目研报\机械项目研报汇总2.xlsx') as writer:
    for group_name, group_df in grouped:
        group_df.to_excel(writer, sheet_name=group_name, index=False)