鱼C论坛

 找回密码
 立即注册
查看: 1141|回复: 37

python处理excel

[复制链接]
发表于 2024-6-28 21:57:07 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
在同一个sheet表中,将每个小表格删除最后两行合并,共用相同的抬头,合并后的表格序号要连续,最后导出到新的excel表中
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-6-28 21:59:50 | 显示全部楼层
没问题,鱼儿别急,我们慢慢来搞定这个问题。这就好比我们做了一大堆小鱼干,现在要把每条鱼减掉尾巴,然后整齐地排列成一盘咸鱼宴。

以下是一步步的做法:

1. **读入Excel文件**:用`pandas`库读取你的Excel文件。
2. **遍历每个小表格**:将每个小表格的最后两行去掉,并且统一拼接成一个大表。
3. **重新编号**:给合并后的大表重新编序。
4. **导出新Excel**:保存成一个新的Excel文件,你可以痛快地享受你的“渔业成果”了。

让我们用代码来实现吧。先装好`pandas`库:
  1. pip install pandas
复制代码


然后,用下面的代码搞定你的需求:

  1. import pandas as pd

  2. # 读取Excel文件
  3. file_path = '你的Excel文件路径.xlsx'
  4. sheet_name = 'Sheet1'  # 确保这是你要处理的那个Sheet表
  5. df = pd.read_excel(file_path, sheet_name=sheet_name)

  6. # 获取抬头
  7. header = df.iloc[0]

  8. # 假设几个小表格之间有空行隔开
  9. # 将合并后的数据放到一个列表中
  10. merged_data = []

  11. # 定义一个临时变量存储单个小表格
  12. temp_table = []

  13. # 遍历表格
  14. for index, row in df.iterrows():
  15.     if row.isnull().all():
  16.         # 如果这一行全是空的,表示一个小表格结束
  17.         if temp_table:
  18.             temp_df = pd.DataFrame(temp_table)
  19.             merged_data.extend(temp_df.iloc[:-2].values.tolist())  # 去掉最后两行
  20.         temp_table = []
  21.     else:
  22.         temp_table.append(row.values.tolist())

  23. # 防止最后一个小表格漏掉
  24. if temp_table:
  25.     temp_df = pd.DataFrame(temp_table)
  26.     merged_data.extend(temp_df.iloc[:-2].values.tolist())

  27. # 创建合并后的DataFrame
  28. merged_df = pd.DataFrame(merged_data, columns=header)

  29. # 添加序号
  30. merged_df.insert(0, '序号', range(1, len(merged_df) + 1))

  31. # 导出到新的Excel中
  32. merged_df.to_excel('合并后的表格.xlsx', index=False)

  33. print("搞定!新的文件名叫做:合并后的表格.xlsx")
复制代码


注意:
- `file_path`变量需要替换成你的Excel文件路径。
- 确保`sheet_name`变量对应的是你需要处理的Sheet表名。
- 如果你的表格不是通过空行分隔的小表格,那需要调整逻辑判断小表格的结束。

这样,你的“小鱼干”就变成了一盘整齐漂亮的“大咸鱼宴”啦!喝杯茶吃块饼干,静静等待代码跑完吧~

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-28 22:02:28 | 显示全部楼层
FishC 发表于 2024-6-28 21:59
没问题,鱼儿别急,我们慢慢来搞定这个问题。这就好比我们做了一大堆小鱼干,现在要把每条鱼减掉尾巴,然后 ...

Traceback (most recent call last):
  File "D:\PyCharm\excel_merge\excel_merge\.venv\Lib\site-packages\extract.py", line 39, in <module>
    merged_df.insert(0, '序号', range(1, len(merged_df) + 1))
  File "D:\anaconda3\Lib\site-packages\pandas\core\frame.py", line 4931, in insert
    raise ValueError(f"cannot insert {column}, already exists")
ValueError: cannot insert 序号, already exists
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-28 22:05:05 | 显示全部楼层
pallas 发表于 2024-06-28 22:02
Traceback (most recent call last):
  File "D:\PyC ...


嘿嘿,鱼儿别着急,这种错误就像你钓到了一条小鱼却发现已经有了鱼钩在嘴里。就是说,你想加个"序号"列,但这个列已经存在了。咱们可以先检查一下,如果已经有了"序号"列,就跳过创建新的"序号"列的步骤。

我们稍微修改下代码,让它更稳妥一点:

  1. import pandas as pd

  2. # 读取Excel文件
  3. file_path = '你的Excel文件路径.xlsx'
  4. sheet_name = 'Sheet1'  # 确保这是你要处理的那个Sheet表
  5. df = pd.read_excel(file_path, sheet_name=sheet_name)

  6. # 获取抬头
  7. header = df.columns.tolist()

  8. # 假设几个小表格之间有空行隔开
  9. # 将合并后的数据放到一个列表中
  10. merged_data = []

  11. # 定义一个临时变量存储单个小表格
  12. temp_table = []

  13. # 遍历表格
  14. for index, row in df.iterrows():
  15.     if row.isnull().all():
  16.         # 如果这一行全是空的,表示一个小表格结束
  17.         if temp_table:
  18.             temp_df = pd.DataFrame(temp_table)
  19.             merged_data.extend(temp_df.iloc[:-2].values.tolist())  # 去掉最后两行
  20.         temp_table = []
  21.     else:
  22.         temp_table.append(row.values.tolist())

  23. # 防止最后一个小表格漏掉
  24. if temp_table:
  25.     temp_df = pd.DataFrame(temp_table)
  26.     merged_data.extend(temp_df.iloc[:-2].values.tolist())

  27. # 创建合并后的DataFrame
  28. merged_df = pd.DataFrame(merged_data, columns=header)

  29. # 添加序号(如果没有的话)
  30. if '序号' not in merged_df.columns:
  31.     merged_df.insert(0, '序号', range(1, len(merged_df) + 1))
  32. else:
  33.     merged_df['序号'] = range(1, len(merged_df) + 1)

  34. # 导出到新的Excel中
  35. merged_df.to_excel('合并后的表格.xlsx', index=False)

  36. print("搞定!新的文件名叫做:合并后的表格.xlsx")
复制代码


这样,代码会先检查是否已经存在"序号"列,如果已经存在,就直接覆盖旧的序号。快试一下吧,希望这次没有“小鱼钩中鱼钩”的情况了!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-28 22:16:19 | 显示全部楼层
  1. import xlwings as xw
  2. import os
  3. import pandas as pd
  4. import openpyxl
  5. import os
  6. #拆分表格

  7. def extract_tables_from_excel(file_path, sheet_name='Sheet1'):
  8.     df = pd.read_excel(file_path, sheet_name=sheet_name)
  9.     tables = []
  10.     temp_df = []

  11.     # 分割逻辑:遇到空行就分割
  12.     for _, row in df.iterrows():
  13.         if row.isnull().all():  # 判断空行
  14.             if temp_df:
  15.                 tables.append(pd.DataFrame(temp_df))
  16.                 temp_df = []
  17.         else:
  18.             temp_df.append(row)

  19.     if temp_df:
  20.         tables.append(pd.DataFrame(temp_df))

  21.     return tables


  22. def merge_tables(merging_tables, existing_tables):
  23.     merged_tables = []
  24.     for new_table, old_table in zip(merging_tables, existing_tables):
  25.         merged_table = pd.concat([old_table, new_table], ignore_index=True)
  26.         merged_tables.append(merged_table)
  27.     return merged_tables


  28. # 主函数
  29. def main(input_files, existing_files, output_dir):
  30.     all_existing_tables = [pd.read_excel(file) for file in existing_files]

  31.     for file in input_files:
  32.         merging_tables = extract_tables_from_excel(file)
  33.         all_existing_tables = merge_tables(merging_tables, all_existing_tables)

  34.     # 输出合并后的表格
  35.     for idx, table in enumerate(all_existing_tables):
  36.         output_file_path = os.path.join(output_dir, f'merged_output_{idx + 1}.xlsx')
  37.         table.to_excel(output_file_path, index=False)
  38.         print(f'Saved merged table to {output_file_path}')


  39. input_files = [r"D:\2024年6月14日周督促会\周督促会-南岸支行(6月14日).xlsx",
  40.              r"D:\2024年6月14日周督促会\周督促会-业务一部(6月14日).xlsx",
  41.              r"D:\2024年6月14日周督促会\周督促会-渝北支行(6月13日).xlsx",
  42.              r"D:\2024年6月14日周督促会\周督促会-九龙坡支行(6月13日).xlsx",
  43.              r"D:\2024年6月14日周督促会\周督促会-高新支行(6月14日).xlsx",
  44.              r"D:\2024年6月14日周督促会\周督促会-巴南支行(6月14日).xlsx",
  45.              r"D:\2024年6月14日周督促会\周督促会-长寿支行(6月14日).xlsx",
  46.              r"D:\2024年6月14日周督促会\周督促会-营业部(6月14日).xlsx",
  47.              r"D:\2024年6月14日周督促会\周督促会-业务二部(6月14日).xlsx",
  48.              r"D:\2024年6月14日周督促会\周督促会-公司业务四部(6月14日).xlsx",
  49.              r"D:\2024年6月14日周督促会\周督促会-拓展一部(6月14日).xlsx"]
  50. existing_files = [r"D:\2024年6月14日周督促会\output_table_1.xlsx",
  51.                       r"D:\2024年6月14日周督促会\output_table_2.xlsx",
  52.                       r"D:\2024年6月14日周督促会\output_table_3.xlsx",
  53.                       r"D:\2024年6月14日周督促会\output_table_4.xlsx",
  54.                       r"D:\2024年6月14日周督促会\output_table_5.xlsx",
  55.                       r"D:\2024年6月14日周督促会\output_table_6.xlsx",
  56.                       r"D:\2024年6月14日周督促会\output_table_7.xlsx",
  57.                       r"D:\2024年6月14日周督促会\output_table_8.xlsx",
  58.                       r"D:\2024年6月14日周督促会\output_table_9.xlsx",
  59.                       r"D:\2024年6月14日周督促会\output_table_10.xlsx",
  60.                       r"D:\2024年6月14日周督促会\output_table_11.xlsx",
  61.                       r"D:\2024年6月14日周督促会\output_table_12.xlsx"]
  62. output_dir = r'D:\2024年6月14日周督促会\统计'

  63. main(input_files, existing_files, output_dir)
复制代码

这个代码运行后为什么表格的第一行会有Unnamed: 1,可以删除掉吗?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-28 22:16:52 | 显示全部楼层
pallas 发表于 2024-06-28 22:16
import xlwings as xw
import os
import pandas as  ...


嘿嘿,鱼儿,这可不是鱼鳞掉到你的盘子里了,而是因为在使用`pandas.DataFrame.to_excel`时,DataFrame的索引会默认作为第一列导出。如果你不需要索引导出,只需设置`index=False`就可以啦。

首先,让我们调整一下函数`extract_tables_from_excel`。然后修改`main`函数,以确保在导出Excel时没有多余的索引。

以下是修正后的代码:

  1. import pandas as pd
  2. import os

  3. # 拆分表格函数
  4. def extract_tables_from_excel(file_path, sheet_name='Sheet1'):
  5.     df = pd.read_excel(file_path, sheet_name=sheet_name)
  6.     tables = []
  7.     temp_df = []

  8.     # 分割逻辑:遇到空行就分割
  9.     for _, row in df.iterrows():
  10.         if row.isnull().all():  # 判断空行
  11.             if temp_df:
  12.                 tables.append(pd.DataFrame(temp_df))
  13.                 temp_df = []
  14.         else:
  15.             temp_df.append(row)

  16.     if temp_df:
  17.         tables.append(pd.DataFrame(temp_df))

  18.     return tables


  19. # 合并表格函数
  20. def merge_tables(merging_tables, existing_tables):
  21.     merged_tables = []
  22.     for new_table, old_table in zip(merging_tables, existing_tables):
  23.         if not old_table.empty:
  24.             merged_table = pd.concat([old_table, new_table], ignore_index=True)
  25.         else:
  26.             merged_table = new_table
  27.         merged_tables.append(merged_table)
  28.     return merged_tables


  29. # 主函数
  30. def main(input_files, existing_files, output_dir):
  31.     all_existing_tables = [pd.read_excel(file) for file in existing_files]

  32.     for file in input_files:
  33.         merging_tables = extract_tables_from_excel(file)
  34.         all_existing_tables = merge_tables(merging_tables, all_existing_tables)

  35.     # 输出合并后的表格
  36.     for idx, table in enumerate(all_existing_tables):
  37.         output_file_path = os.path.join(output_dir, f'merged_output_{idx + 1}.xlsx')
  38.         table.to_excel(output_file_path, index=False)  # 确保 index=False
  39.         print(f'Saved merged table to {output_file_path}')


  40. # 示例的输入文件路径列表
  41. input_files = [r'路径1.xlsx', r'路径2.xlsx']
  42. existing_files = [r'已有路径1.xlsx', r'已有路径2.xlsx']
  43. output_dir = r'D:\2024年6月14日周督促会\统计'

  44. main(input_files, existing_files, output_dir)
复制代码


### 解释:
1. **提取表格**:`extract_tables_from_excel` 函数把每个表格从Excel文件中拆分出来,遇到空行就分割。
2. **合并表格**:`merge_tables` 函数将新表格和现有表格进行合并。
3. **主函数**:`main` 函数读取所有输入文件,并调用拆分和合并函数处理数据,然后将结果保存到指定目录下的新Excel文件中。
4. **防止索引输出**:`table.to_excel(output_file_path, index=False)` 这行代码确保了导出Excel时不会带上多余的索引。

这样,你的表格应该干净整洁,没有多余的“Unnamed”列。快试试吧,再次祝你“小鱼干”大丰收!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-28 22:19:16 | 显示全部楼层
FishC 发表于 2024-6-28 22:16
嘿嘿,鱼儿,这可不是鱼鳞掉到你的盘子里了,而是因为在使用`pandas.DataFrame.to_excel`时,DataFrame ...

还是有Unnamed
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-28 22:19:47 | 显示全部楼层


啊,还没摆脱这个“讨人厌的乘客”——`Unnamed`列吗?别急,咱们再检查一下数据处理的每一步。

这个问题通常是因为在将DataFrame对象添加到列表时,无意中添加了一些额外的索引或者标题行。我们可以通过打印一些调试信息来找到错误发生的位置。

请确保你在合并表格时没有重复添加标题行,并且在输出时也没有任何多余的索引。

这里有修正后的代码,并增加一些调试信息,帮助我们确定问题所在:

  1. import pandas as pd
  2. import os

  3. # 拆分表格函数
  4. def extract_tables_from_excel(file_path, sheet_name='Sheet1'):
  5.     df = pd.read_excel(file_path, sheet_name=sheet_name)
  6.     tables = []
  7.     temp_df = []

  8.     # 分割逻辑:遇到空行就分割
  9.     for _, row in df.iterrows():
  10.         if row.isnull().all():  # 判断空行
  11.             if temp_df:
  12.                 tables.append(pd.DataFrame(temp_df))
  13.                 temp_df = []
  14.         else:
  15.             temp_df.append(row)

  16.     if temp_df:
  17.         tables.append(pd.DataFrame(temp_df))

  18.     return tables


  19. # 合并表格函数
  20. def merge_tables(merging_tables, existing_tables):
  21.     merged_tables = []
  22.     for new_table, old_table in zip(merging_tables, existing_tables):
  23.         old_table = old_table.dropna(how='all')  # 删除旧表格里的空行,确保合并时不出问题
  24.         merged_table = pd.concat([old_table, new_table.iloc[:-2]], ignore_index=True)  # 去掉新表格最后两行
  25.         merged_tables.append(merged_table)
  26.     return merged_tables


  27. # 主函数
  28. def main(input_files, existing_files, output_dir):
  29.     all_existing_tables = []

  30.     for file in input_files:
  31.         merging_tables = extract_tables_from_excel(file)
  32.         all_existing_tables = merge_tables(merging_tables, all_existing_tables)

  33.     # 输出合并后的表格
  34.     for idx, table in enumerate(all_existing_tables):
  35.         print(f"Exporting table {idx + 1} with columns: {table.columns.tolist()}")  # 调试信息:打印列名
  36.         output_file_path = os.path.join(output_dir, f'merged_output_{idx + 1}.xlsx')
  37.         table.to_excel(output_file_path, index=False)  # 确保 index=False
  38.         print(f'Saved merged table to {output_file_path}')


  39. # 示例的输入文件路径列表
  40. input_files = []  # 列表里写入你的输入文件路径
  41. existing_files = []  # 如果有现成的表格需要合并,在这里填入路径
  42. output_dir = r'D:\2024年6月14日周督促会\统计'

  43. main(input_files, existing_files, output_dir)
复制代码


### 关键点
1. **去掉旧表格中的空行**:`old_table = old_table.dropna(how='all')`确保在旧表格中没有多余的空行。
2. **去掉新表格的最后两行**:`new_table.iloc[:-2]`确保新数据表中最后两行被剔除。
3. **打印列名进行调试**:`print(f"Exporting table {idx + 1} with columns: {table.columns.tolist()}")`这行代码会在导出之前打印每个表格的列名,帮助我们确认没有多余的“Unnamed”列。

再试试这些调整,它们应该能有效地解决“Unnamed”列的问题。如果还有问题,我们可以继续调试和改进。抓紧时间让你的“小鱼干”变得更漂亮吧!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-28 22:22:30 | 显示全部楼层
FishC 发表于 2024-6-28 22:19
啊,还没摆脱这个“讨人厌的乘客”——`Unnamed`列吗?别急,咱们再检查一下数据处理的每一步。

这 ...

他是第一行有Unnamed,不是列
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-28 22:22:44 | 显示全部楼层
pallas 发表于 2024-06-28 22:22
他是第一行有Unnamed,不是列


啊,我明白了,鱼儿!原来问题出在标题行,也就是当你从Excel读取数据时,Pandas可能加了多余的标题行。

我们可以通过指定正确的header来解决这个问题。尝试以下方法读取Excel文件时,指定`header`参数:

  1. def extract_tables_from_excel(file_path, sheet_name='Sheet1'):
  2.     df = pd.read_excel(file_path, sheet_name=sheet_name, header=0)  # 确保读取时使用正确的表头
  3.     tables = []
  4.     temp_df = []

  5.     # 分割逻辑:遇到空行就分割
  6.     for _, row in df.iterrows():
  7.         if row.isnull().all():  # 判断空行
  8.             if temp_df:
  9.                 tables.append(pd.DataFrame(temp_df))
  10.                 temp_df = []
  11.         else:
  12.             temp_df.append(row)

  13.     if temp_df:
  14.         tables.append(pd.DataFrame(temp_df))

  15.     return tables

  16. def merge_tables(merging_tables, existing_tables):
  17.     merged_tables = []
  18.     for new_table, old_table in zip(merging_tables, existing_tables):
  19.         merged_table = pd.concat([old_table.iloc[:-2], new_table.iloc[:-2]], ignore_index=True)  # 删除最后两行再合并
  20.         merged_tables.append(merged_table)
  21.     return merged_tables

  22. # 主函数
  23. def main(input_files, existing_files, output_dir):
  24.     all_existing_tables = []

  25.     for file in input_files:
  26.         merging_tables = extract_tables_from_excel(file)
  27.         all_existing_tables = merge_tables(merging_tables, all_existing_tables)

  28.     # 输出合并后的表格
  29.     for idx, table in enumerate(all_existing_tables):
  30.         output_file_path = os.path.join(output_dir, f'merged_output_{idx + 1}.xlsx')
  31.         table.to_excel(output_file_path, index=False, header=True)  # 确保导出时保留表头
  32.         print(f'Saved merged table to {output_file_path}')

  33. input_files = ['path_to_your_input_file_1.xlsx', 'path_to_your_input_file_2.xlsx']
  34. existing_files = []  # 如果有现存的表格可以放在这里
  35. output_dir = r'D:\2024年6月14日周督促会\统计'

  36. main(input_files, existing_files, output_dir)
复制代码


通过这种方式,我们明确地告诉`pandas`在读取和导出数据时如何处理表头。希望这次没有“Unnamed”来捣乱啦!如果还有其他问题,尽管告诉我,我们鱼油一同作战!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-28 23:31:44 | 显示全部楼层
  1. import xlwings as xw
  2. import pandas as pd
  3. import openpyxl
  4. import os
  5. #拆分表格

  6. def extract_tables_from_excel(file_path, sheet_name='Sheet1'):
  7.     df = pd.read_excel(file_path, sheet_name=sheet_name)
  8.     tables = []
  9.     temp_df = []

  10.     # 分割逻辑:遇到空行就分割
  11.     for _, row in df.iterrows():
  12.         if row.isnull().all():  # 判断空行
  13.             if temp_df:
  14.                 tables.append(pd.DataFrame(temp_df))
  15.                 temp_df = []
  16.         else:
  17.             temp_df.append(row)

  18.     if temp_df:
  19.         tables.append(pd.DataFrame(temp_df))

  20.     return tables


  21. def merge_tables(merging_tables, existing_tables):
  22.     merged_tables = []
  23.     for new_table, old_table in zip(merging_tables, existing_tables):
  24.         merged_table = pd.concat([old_table, new_table], ignore_index=True)
  25.         merged_tables.append(merged_table)
  26.     return merged_tables


  27. # 主函数
  28. def main(input_files, existing_files, output_dir):
  29.     all_existing_tables = [pd.read_excel(file) for file in existing_files]

  30.     for file in input_files:
  31.         merging_tables = extract_tables_from_excel(file)
  32.         all_existing_tables = merge_tables(merging_tables, all_existing_tables)

  33.     # 输出合并后的表格
  34.     for idx, table in enumerate(all_existing_tables):
  35.         output_file_path = os.path.join(output_dir, f'merged_output_{idx + 1}.xlsx')
  36.         table.to_excel(output_file_path, index=False)
  37.         print(f'Saved merged table to {output_file_path}')


  38. input_files = [r"D:\2024年6月14日周督促会\周督促会-南岸支行(6月14日).xlsx",
  39.                r"D:\2024年6月14日周督促会\周督促会-业务一部(6月14日).xlsx",
  40.                r"D:\2024年6月14日周督促会\周督促会-渝北支行(6月13日).xlsx",
  41.                r"D:\2024年6月14日周督促会\周督促会-九龙坡支行(6月13日).xlsx",
  42.                r"D:\2024年6月14日周督促会\周督促会-高新支行(6月14日).xlsx",
  43.                r"D:\2024年6月14日周督促会\周督促会-巴南支行(6月14日).xlsx",
  44.                r"D:\2024年6月14日周督促会\周督促会-长寿支行(6月14日).xlsx",
  45.                r"D:\2024年6月14日周督促会\周督促会-营业部(6月14日).xlsx",
  46.                r"D:\2024年6月14日周督促会\周督促会-业务二部(6月14日).xlsx",
  47.                r"D:\2024年6月14日周督促会\周督促会-公司业务四部(6月14日).xlsx",
  48.                r"D:\2024年6月14日周督促会\周督促会-拓展一部(6月14日).xlsx"]
  49. existing_files = [r"D:\2024年6月14日周督促会\next\output_table_1.xlsx",
  50.                   r"D:\2024年6月14日周督促会\next\output_table_2.xlsx",
  51.                   r"D:\2024年6月14日周督促会\next\output_table_3.xlsx",
  52.                   r"D:\2024年6月14日周督促会\next\output_table_4.xlsx",
  53.                   r"D:\2024年6月14日周督促会\next\output_table_5.xlsx",
  54.                   r"D:\2024年6月14日周督促会\next\output_table_6.xlsx",
  55.                   r"D:\2024年6月14日周督促会\next\output_table_7.xlsx",
  56.                   r"D:\2024年6月14日周督促会\next\output_table_8.xlsx",
  57.                   r"D:\2024年6月14日周督促会\next\output_table_9.xlsx",
  58.                   r"D:\2024年6月14日周督促会\next\output_table_10.xlsx",
  59.                   r"D:\2024年6月14日周督促会\next\output_table_11.xlsx",
  60.                   r"D:\2024年6月14日周督促会\next\output_table_12.xlsx",
  61.                   r"D:\2024年6月14日周督促会\next\output_table_13.xlsx",
  62.                   r"D:\2024年6月14日周督促会\next\output_table_14.xlsx",
  63.                   r"D:\2024年6月14日周督促会\next\output_table_15.xlsx",
  64.                   r"D:\2024年6月14日周督促会\next\output_table_16.xlsx",
  65.                   r"D:\2024年6月14日周督促会\next\output_table_17.xlsx",
  66.                   r"D:\2024年6月14日周督促会\next\output_table_18.xlsx",
  67.                   r"D:\2024年6月14日周督促会\next\output_table_19.xlsx",
  68.                   r"D:\2024年6月14日周督促会\next\output_table_20.xlsx",
  69.                   r"D:\2024年6月14日周督促会\next\output_table_21.xlsx",
  70.                   r"D:\2024年6月14日周督促会\next\output_table_22.xlsx",]
  71. output_dir = r'D:\2024年6月14日周督促会\first'

  72. main(input_files, existing_files, output_dir)

复制代码

如何让提出来的小表格按空行分隔开
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-28 23:32:22 | 显示全部楼层
pallas 发表于 2024-06-28 23:31
import xlwings as xw
import pandas as pd
import  ...


好哒,鱼儿,我明白了!你想要把大表格按照空行分割成多个小表格,并将每个小表格的最后两行删除,最后将这些小表格合并成一个表格并保存到新的Excel文件中。以下是修改过的代码,其中包括完整的步骤和注释来帮助你理解。

### 完整的代码示例

  1. import pandas as pd
  2. import os

  3. # 拆分表格函数
  4. def extract_tables_from_excel(file_path, sheet_name='Sheet1'):
  5.     df = pd.read_excel(file_path, sheet_name=sheet_name, header=0)
  6.     tables = []
  7.     temp_df = []

  8.     # 分割逻辑:遇到空行就分割
  9.     for _, row in df.iterrows():
  10.         if row.isnull().all():  # 判断空行
  11.             if temp_df:
  12.                 temp_df = pd.DataFrame(temp_df).iloc[:-2]  # 删除最后两行
  13.                 tables.append(temp_df)
  14.                 temp_df = []
  15.         else:
  16.             temp_df.append(row)

  17.     if temp_df:
  18.         temp_df = pd.DataFrame(temp_df).iloc[:-2]  # 删除最后两行
  19.         tables.append(temp_df)

  20.     return tables

  21. # 合并表格函数
  22. def merge_tables(tables):
  23.     merged_table = pd.concat(tables, ignore_index=True)
  24.     return merged_table

  25. # 主函数
  26. def main(input_files, output_file):
  27.     all_tables = []

  28.     for file in input_files:
  29.         tables = extract_tables_from_excel(file)
  30.         all_tables.extend(tables)

  31.     merged_table = merge_tables(all_tables)

  32.     # 添加序号列
  33.     merged_table.insert(0, '序号', range(1, len(merged_table) + 1))

  34.     # 输出合并后的表格
  35.     merged_table.to_excel(output_file, index=False)
  36.     print(f'Saved merged table to {output_file}')

  37. # 输入文件列表和输出文件路径
  38. input_files = [
  39.     r'D:\你的路径\文件1.xlsx',
  40.     r'D:\你的路径\文件2.xlsx'
  41. ]
  42. output_file = r'D:\2024年6月14日周督促会\first\merged_output.xlsx'

  43. main(input_files, output_file)
复制代码


### 解释
1. **拆分表格函数 `extract_tables_from_excel`**:
   - 读取Excel文件并将其转为DataFrame。
   - 使用空行作为分割点,将大表格拆分成多个小表格。
   - 每个小表格删除最后两行。

2. **合并表格函数 `merge_tables`**:
   - 将所有小表格合并为一个大表格。

3. **主函数 `main`**:
   - 读取输入文件列表,并将每个文件中的表格提取出来。
   - 合并所有表格。
   - 添加序号列。
   - 将最终合并的表格输出到一个新的Excel文件。

4. **处理输入和输出**:
   - 指定输入文件列表和输出文件路径。

这样一来,运行这个脚本就能得到一个合并后的表格,并且每个小表格的最后两行都会被删除,还会有一个连续的序号列。

希望这次能顺利帮你解决问题!如果还有其他问题,尽管问我哦。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-28 23:39:37 | 显示全部楼层
提取多个excel表中同一个sheet表中不同的小表格,将不同的小表格分别合并在一起,且用空行隔开,导出为新的excel
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-28 23:40:08 | 显示全部楼层
pallas 发表于 2024-06-28 23:39
提取多个excel表中同一个sheet表中不同的小表格,将不 ...


好呀,鱼儿,这个任务就像把各种小鱼干整齐地排列到一个大盘子里,再用几片海带隔开。以下是详细步骤和代码来实现这个需求:

1. **读取多个Excel文件**,从每个文件的同一个Sheet中提取小表格。
2. **按空行分割**每个Sheet中的小表格。
3. **合并所有提取的小表格**,并在每个小表格之间加上空行。
4. **导出到新的Excel文件**。

这里是实现这个任务的代码:

  1. import pandas as pd
  2. import os

  3. def extract_tables_from_excel(file_path, sheet_name='Sheet1'):
  4.     df = pd.read_excel(file_path, sheet_name=sheet_name)
  5.     tables = []
  6.     temp_df = []

  7.     # 分割逻辑:遇到空行就分割
  8.     for _, row in df.iterrows():
  9.         if row.isnull().all():  # 判断空行
  10.             if temp_df:
  11.                 tables.append(pd.DataFrame(temp_df))
  12.                 temp_df = []
  13.         else:
  14.             temp_df.append(row)

  15.     if temp_df:
  16.         tables.append(pd.DataFrame(temp_df))

  17.     return tables

  18. def merge_tables(tables_list):
  19.     merged_df = pd.DataFrame()
  20.     for tables in tables_list:
  21.         for table in tables:
  22.             merged_df = pd.concat([merged_df, table, pd.DataFrame([[""] * len(table.columns)])], ignore_index=True)
  23.     return merged_df

  24. def main(input_files, output_file):
  25.     all_tables = []

  26.     for file in input_files:
  27.         tables = extract_tables_from_excel(file)
  28.         all_tables.append(tables)

  29.     merged_df = merge_tables(all_tables)
  30.     merged_df.to_excel(output_file, index=False, header=False)
  31.     print(f'Saved merged table to {output_file}')

  32. input_files = [r'path_to_excel_1.xlsx', r'path_to_excel_2.xlsx', r'path_to_excel_3.xlsx']  # 这里替换为你的文件路径
  33. output_file = r'path_to_output.xlsx'  # 这里替换为你的输出文件路径

  34. main(input_files, output_file)
复制代码


**说明**:
1. **`extract_tables_from_excel`**:从Excel文件中提取表格,根据空行进行分割。
2. **`merge_tables`**:将提取的表格合并,并在每个表格之间加上空行。
3. **`main`**:读取所有输入文件,提取表格,合并并保存到新的Excel文件。

你可以根据自己的文件路径修改 `input_files` 和 `output_file` 变量。这样就可以按需求处理并保存新的Excel表格了。希望这个方法能解决你的问题,祝你“钓”鱼愉快!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-28 23:50:21 | 显示全部楼层
FishC 发表于 2024-6-28 23:40
好呀,鱼儿,这个任务就像把各种小鱼干整齐地排列到一个大盘子里,再用几片海带隔开。以下是详细步骤和 ...

生成表格的第一行有Unnamed: 1,如何不让其生成
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-28 23:50:41 | 显示全部楼层
pallas 发表于 2024-06-28 23:50
生成表格的第一行有Unnamed: 1,如何不让其生成


明白啦,鱼儿,看来这个`Unnamed: 1`是在处理过程中无意生成的。我们需要仔细检查一下数据处理的各个环节,并确保不会多生成标题行。

以下是完整的代码示例,它按空行分割多个Excel文件中的表格,并合并在一起导出,同时避免出现`Unnamed: 1`这样的多余标题行:

  1. import pandas as pd
  2. import os

  3. # 提取表格
  4. def extract_tables_from_excel(file_path, sheet_name='Sheet1'):
  5.     df = pd.read_excel(file_path, sheet_name=sheet_name, header=None)  # header=None防止自动识别表头
  6.     tables = []
  7.     temp_df = []

  8.     # 分割逻辑:遇到空行就分割
  9.     for _, row in df.iterrows():
  10.         if row.isnull().all():  # 判断空行
  11.             if temp_df:
  12.                 tables.append(pd.DataFrame(temp_df).reset_index(drop=True))
  13.                 temp_df = []
  14.         else:
  15.             temp_df.append(row)

  16.     if temp_df:
  17.         tables.append(pd.DataFrame(temp_df).reset_index(drop=True))

  18.     return tables

  19. # 合并表格,并用空行隔开
  20. def merge_tables(tables):
  21.     merged_df = pd.DataFrame()
  22.     for table in tables:
  23.         if not merged_df.empty:
  24.             merged_df = pd.concat([merged_df, pd.DataFrame([[]]), table], ignore_index=True)
  25.         else:
  26.             merged_df = table

  27.     return merged_df

  28. # 主函数
  29. def main(input_files, output_file):
  30.     all_tables = []

  31.     for file in input_files:
  32.         tables = extract_tables_from_excel(file)
  33.         all_tables.extend(tables)

  34.     merged_df = merge_tables(all_tables)

  35.     # 输出合并后的表格
  36.     merged_df.to_excel(output_file, index=False, header=False)  # header=False防止生成多余的列名
  37.     print(f'Saved merged table to {output_file}')

  38. # 示例文件路径列表
  39. input_files = [
  40.     '文件路径1.xlsx',
  41.     '文件路径2.xlsx'
  42. ]
  43. output_file = r'合并后的文件路径.xlsx'

  44. main(input_files, output_file)
复制代码


### 代码解释:
1. **`extract_tables_from_excel`**函数:
    - 读取Excel文件并将每个表格按空行分割成小表格。
    - 使用`header=None`读取数据,防止Pandas自动识别第一行作为标题行。
    - 使用`reset_index(drop=True)`重置每个DataFrame的小表格的索引,防止产生多余的索引。

2. **`merge_tables`**函数:
    - 将所有小表格合并到一个DataFrame对象中,并在不同的小表格之间插入空行。

3. **`main`**函数:
    - 读取所有输入文件并提取小表格。
    - 合并所有提取的小表格,并将合并后的表格保存到新的Excel文件中。
    - 使用`header=False`来防止新的Excel文件生成多余的列名。

这样做的话,应该可以避免你提到的`Unnamed: 1`问题。如果还有问题,请告诉我,我们一起解决!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-29 00:21:19 | 显示全部楼层
FishC 发表于 2024-6-28 21:59
没问题,鱼儿别急,我们慢慢来搞定这个问题。这就好比我们做了一大堆小鱼干,现在要把每条鱼减掉尾巴,然后 ...

抬头要共用
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-29 00:21:44 | 显示全部楼层


好哒,鱼儿,那么我们要确保所有表格共用相同的标题行,同时按空行分割每个Excel文件中的小表格,再合并在一起。我们需要以下几个步骤:

1. **读取多个Excel文件**,从每个文件中提取小表格。
2. **按空行分割**:将每个文件中的小表格按空行分割开。
3. **删除每个小表格的最后两行**。
4. **合并带有相同标题的小表格**,用空行隔开。
5. **导出最终结果为新的Excel文件**。

这是修正后的代码:

  1. import pandas as pd
  2. import os

  3. # 提取excel中的小表格,按空行分割
  4. def extract_tables_from_excel(file_path, sheet_name='Sheet1'):
  5.     df = pd.read_excel(file_path, sheet_name=sheet_name)
  6.     tables = []
  7.     temp_df = []

  8.     header = None

  9.     # 分割逻辑:遇到空行就分割
  10.     for _, row in df.iterrows():
  11.         if row.isnull().all():  # 判断空行
  12.             if temp_df:
  13.                 if not header:
  14.                     header = temp_df[0].index.tolist()
  15.                 table = pd.DataFrame(temp_df)
  16.                 tables.append(table)
  17.                 temp_df = []
  18.         else:
  19.             temp_df.append(row)

  20.     if temp_df:
  21.         if not header:
  22.             header = temp_df[0].index.tolist()
  23.         table = pd.DataFrame(temp_df)
  24.         tables.append(table)

  25.     return tables, header

  26. # 删除每个小表格的最后两行
  27. def remove_last_two_rows(tables):
  28.     return [table.iloc[:-2] for table in tables if len(table) > 2]

  29. # 合并表格,使用相同的抬头
  30. def merge_tables(tables, header):
  31.     merged_table = pd.DataFrame(columns=header)
  32.     for table in tables:
  33.         merged_table = pd.concat([merged_table, table], ignore_index=True)
  34.         # 添加一个全为NaN的空行以分隔表格
  35.         empty_row = pd.Series([None]*len(header), index=header)
  36.         merged_table = merged_table.append(empty_row, ignore_index=True)

  37.     return merged_table

  38. # 主函数
  39. def main(input_files, output_file):
  40.     all_tables = []
  41.     common_header = None

  42.     for file in input_files:
  43.         tables, header = extract_tables_from_excel(file)
  44.         if common_header is None:
  45.             common_header = header
  46.         tables = remove_last_two_rows(tables)
  47.         all_tables.extend(tables)

  48.     final_merged_table = merge_tables(all_tables, common_header)

  49.     # 输出合并后的表格
  50.     final_merged_table.to_excel(output_file, index=False)
  51.     print(f'Saved merged table to {output_file}')

  52. # 输入文件和输出文件路径
  53. input_files = ['file1.xlsx', 'file2.xlsx']  # 将这列表替换为实际的Excel文件路径
  54. output_file = r'D:\output\merged_output.xlsx'

  55. main(input_files, output_file)
复制代码


### 注意事项:

1. **输入文件路径**:确保`input_files`列表中包含你所有需要处理的Excel文件路径。
2. **输出文件路径**:设置`output_file`为你希望保存合并后文件的路径。

这样,各个Excel文件中的同一Sheet会被读取,按空行分割成小表格,删除每个小表格的最后两行,并且汇总到一起,用空行隔开。最终结果会保存到指定的输出文件中。标题行会保持一致,不会出现`Unnamed: 1`。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-29 00:34:40 | 显示全部楼层
FishC 发表于 2024-6-29 00:21
好哒,鱼儿,那么我们要确保所有表格共用相同的标题行,同时按空行分割每个Excel文件中的小表格,再合 ...

Traceback (most recent call last):
  File "D:\PyCharm\excel_merge\excel_merge\.venv\Lib\site-packages\extract.py", line 69, in <module>
    main(input_files, output_file)
  File "D:\PyCharm\excel_merge\excel_merge\.venv\Lib\site-packages\extract.py", line 59, in main
    final_merged_table = merge_tables(all_tables, common_header)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\PyCharm\excel_merge\excel_merge\.venv\Lib\site-packages\extract.py", line 43, in merge_tables
    merged_table = merged_table.append(empty_row, ignore_index=True)
                   ^^^^^^^^^^^^^^^^^^^
  File "D:\anaconda3\Lib\site-packages\pandas\core\generic.py", line 6204, in __getattr__
    return object.__getattribute__(self, name)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'DataFrame' object has no attribute 'append'. Did you mean: '_append'?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-29 00:35:17 | 显示全部楼层
pallas 发表于 2024-06-29 00:34
Traceback (most recent call last):
  File "D:\PyC ...


看样子,你遇到了`pandas`的版本问题。在`pandas`的新版本中,`DataFrame`对象的`append`方法已经被弃用了,我们需要用其他方法来实现类似功能。

为了确保你能成功地提取并合并多个Excel表格中的小表格,同时删除多余的`Unnamed`列并保持相同的标题行,这里是修改后的完整代码:

  1. import pandas as pd
  2. import os

  3. def extract_tables_from_excel(file_path, sheet_name='Sheet1'):
  4.     # 读取 Excel 文件
  5.     df = pd.read_excel(file_path, sheet_name=sheet_name, header=0)
  6.     tables = []
  7.     temp_df = []

  8.     # 分割逻辑:遇到空行就分割
  9.     for _, row in df.iterrows():
  10.         if row.isnull().all():  # 判断空行
  11.             if temp_df:
  12.                 tables.append(pd.DataFrame(temp_df))
  13.                 temp_df = []
  14.         else:
  15.             temp_df.append(row)

  16.     if temp_df:
  17.         tables.append(pd.DataFrame(temp_df))

  18.     return tables

  19. def merge_tables(tables, header):
  20.     # 初始化一个空的 DataFrame 来存储合并后的表格
  21.     merged_table = pd.DataFrame(columns=header)
  22.    
  23.     for table in tables:
  24.         # 删除最后两行
  25.         table = table.iloc[:-2, :]
  26.         # 添加到合并的 DataFrame 中
  27.         merged_table = pd.concat([merged_table, table], ignore_index=True)
  28.         # 添加一个空行分隔符
  29.         empty_row = pd.DataFrame([[""] * len(header)], columns=header)
  30.         merged_table = pd.concat([merged_table, empty_row], ignore_index=True)

  31.     return merged_table

  32. def main(input_files, output_file):
  33.     all_tables = []
  34.     common_header = None

  35.     for file in input_files:
  36.         tables = extract_tables_from_excel(file)
  37.         if common_header is None and tables:
  38.             common_header = tables[0].columns.tolist()
  39.         all_tables.extend(tables)

  40.     if common_header:
  41.         final_merged_table = merge_tables(all_tables, common_header)
  42.         # 删除所有列名为 'Unnamed' 的列
  43.         final_merged_table = final_merged_table.loc[:, ~final_merged_table.columns.str.contains('^Unnamed')]
  44.         final_merged_table.to_excel(output_file, index=False)
  45.         print(f'Saved merged table to {output_file}')
  46.     else:
  47.         print("No tables found to merge.")

  48. input_files = [
  49.     # 这里填入你的Excel文件路径列表
  50.     r'path_to_excel_file_1.xlsx',
  51.     r'path_to_excel_file_2.xlsx'
  52. ]
  53. output_file = r'path_to_output_file.xlsx'

  54. main(input_files, output_file)
复制代码


### 代码说明

1. **extract_tables_from_excel**:这个函数从Excel文件的指定Sheet中提取小表格。
2. **merge_tables**:这个函数将提取的小表格合并到一个大表格中,并在每个小表格之间添加一个空行。
3. **main**:主函数,负责读取文件、提取表格、合并表格并输出到新的Excel文件。

### 运行此代码

1. 将`input_files`列表中的路径替换为实际Excel文件的路径。
2. 将`output_file`的路径替换为你希望保存输出文件的路径。
3. 运行脚本。

这个脚本应该可以帮助你解决问题,并避免生成多余的`Unnamed`列。如果有任何问题或需要进一步的调整,请随时告诉我!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-21 15:05

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表