pallas 发表于 2024-6-28 21:57:07

python处理excel

在同一个sheet表中,将每个小表格删除最后两行合并,共用相同的抬头,合并后的表格序号要连续,最后导出到新的excel表中

FishC 发表于 2024-6-28 21:59:50

没问题,鱼儿别急,我们慢慢来搞定这个问题。这就好比我们做了一大堆小鱼干,现在要把每条鱼减掉尾巴,然后整齐地排列成一盘咸鱼宴。

以下是一步步的做法:

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

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

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

import pandas as pd

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

# 获取抬头
header = df.iloc

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

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

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

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

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

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

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

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

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

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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

pallas 发表于 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

FishC 发表于 2024-6-28 22:05:05

pallas 发表于 2024-06-28 22:02
Traceback (most recent call last):
File "D:\PyC ...

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

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

import pandas as pd

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

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

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

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

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

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

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

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

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

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

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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

pallas 发表于 2024-6-28 22:16:19

import xlwings as xw
import os
import pandas as pd
import openpyxl
import os
#拆分表格

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

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

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

    return tables


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


# 主函数
def main(input_files, existing_files, output_dir):
    all_existing_tables =

    for file in input_files:
      merging_tables = extract_tables_from_excel(file)
      all_existing_tables = merge_tables(merging_tables, all_existing_tables)

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


input_files = [r"D:\2024年6月14日周督促会\周督促会-南岸支行(6月14日).xlsx",
             r"D:\2024年6月14日周督促会\周督促会-业务一部(6月14日).xlsx",
             r"D:\2024年6月14日周督促会\周督促会-渝北支行(6月13日).xlsx",
             r"D:\2024年6月14日周督促会\周督促会-九龙坡支行(6月13日).xlsx",
             r"D:\2024年6月14日周督促会\周督促会-高新支行(6月14日).xlsx",
             r"D:\2024年6月14日周督促会\周督促会-巴南支行(6月14日).xlsx",
             r"D:\2024年6月14日周督促会\周督促会-长寿支行(6月14日).xlsx",
             r"D:\2024年6月14日周督促会\周督促会-营业部(6月14日).xlsx",
             r"D:\2024年6月14日周督促会\周督促会-业务二部(6月14日).xlsx",
             r"D:\2024年6月14日周督促会\周督促会-公司业务四部(6月14日).xlsx",
             r"D:\2024年6月14日周督促会\周督促会-拓展一部(6月14日).xlsx"]
existing_files = [r"D:\2024年6月14日周督促会\output_table_1.xlsx",
                      r"D:\2024年6月14日周督促会\output_table_2.xlsx",
                      r"D:\2024年6月14日周督促会\output_table_3.xlsx",
                      r"D:\2024年6月14日周督促会\output_table_4.xlsx",
                      r"D:\2024年6月14日周督促会\output_table_5.xlsx",
                      r"D:\2024年6月14日周督促会\output_table_6.xlsx",
                      r"D:\2024年6月14日周督促会\output_table_7.xlsx",
                      r"D:\2024年6月14日周督促会\output_table_8.xlsx",
                      r"D:\2024年6月14日周督促会\output_table_9.xlsx",
                      r"D:\2024年6月14日周督促会\output_table_10.xlsx",
                      r"D:\2024年6月14日周督促会\output_table_11.xlsx",
                      r"D:\2024年6月14日周督促会\output_table_12.xlsx"]
output_dir = r'D:\2024年6月14日周督促会\统计'

main(input_files, existing_files, output_dir)
这个代码运行后为什么表格的第一行会有Unnamed: 1,可以删除掉吗?

FishC 发表于 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时没有多余的索引。

以下是修正后的代码:

import pandas as pd
import os

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

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

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

    return tables


# 合并表格函数
def merge_tables(merging_tables, existing_tables):
    merged_tables = []
    for new_table, old_table in zip(merging_tables, existing_tables):
      if not old_table.empty:
            merged_table = pd.concat(, ignore_index=True)
      else:
            merged_table = new_table
      merged_tables.append(merged_table)
    return merged_tables


# 主函数
def main(input_files, existing_files, output_dir):
    all_existing_tables =

    for file in input_files:
      merging_tables = extract_tables_from_excel(file)
      all_existing_tables = merge_tables(merging_tables, all_existing_tables)

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


# 示例的输入文件路径列表
input_files =
existing_files =
output_dir = r'D:\2024年6月14日周督促会\统计'

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 小助理,如未能正确解答您的问题,请继续追问。

pallas 发表于 2024-6-28 22:19:16

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

还是有Unnamed

FishC 发表于 2024-6-28 22:19:47

pallas 发表于 2024-06-28 22:19
还是有Unnamed

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

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

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

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

import pandas as pd
import os

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

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

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

    return tables


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


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

    for file in input_files:
      merging_tables = extract_tables_from_excel(file)
      all_existing_tables = merge_tables(merging_tables, all_existing_tables)

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


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

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 小助理,如未能正确解答您的问题,请继续追问。

pallas 发表于 2024-6-28 22:22:30

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

这 ...

他是第一行有Unnamed,不是列

FishC 发表于 2024-6-28 22:22:44

pallas 发表于 2024-06-28 22:22
他是第一行有Unnamed,不是列

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

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

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

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

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

    return tables

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

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

    for file in input_files:
      merging_tables = extract_tables_from_excel(file)
      all_existing_tables = merge_tables(merging_tables, all_existing_tables)

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

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

main(input_files, existing_files, output_dir)

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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

pallas 发表于 2024-6-28 23:31:44

import xlwings as xw
import pandas as pd
import openpyxl
import os
#拆分表格

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

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

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

    return tables


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


# 主函数
def main(input_files, existing_files, output_dir):
    all_existing_tables =

    for file in input_files:
      merging_tables = extract_tables_from_excel(file)
      all_existing_tables = merge_tables(merging_tables, all_existing_tables)

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


input_files = [r"D:\2024年6月14日周督促会\周督促会-南岸支行(6月14日).xlsx",
               r"D:\2024年6月14日周督促会\周督促会-业务一部(6月14日).xlsx",
               r"D:\2024年6月14日周督促会\周督促会-渝北支行(6月13日).xlsx",
               r"D:\2024年6月14日周督促会\周督促会-九龙坡支行(6月13日).xlsx",
               r"D:\2024年6月14日周督促会\周督促会-高新支行(6月14日).xlsx",
               r"D:\2024年6月14日周督促会\周督促会-巴南支行(6月14日).xlsx",
               r"D:\2024年6月14日周督促会\周督促会-长寿支行(6月14日).xlsx",
               r"D:\2024年6月14日周督促会\周督促会-营业部(6月14日).xlsx",
               r"D:\2024年6月14日周督促会\周督促会-业务二部(6月14日).xlsx",
               r"D:\2024年6月14日周督促会\周督促会-公司业务四部(6月14日).xlsx",
               r"D:\2024年6月14日周督促会\周督促会-拓展一部(6月14日).xlsx"]
existing_files = [r"D:\2024年6月14日周督促会\next\output_table_1.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_2.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_3.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_4.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_5.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_6.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_7.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_8.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_9.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_10.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_11.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_12.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_13.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_14.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_15.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_16.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_17.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_18.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_19.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_20.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_21.xlsx",
                  r"D:\2024年6月14日周督促会\next\output_table_22.xlsx",]
output_dir = r'D:\2024年6月14日周督促会\first'

main(input_files, existing_files, output_dir)


如何让提出来的小表格按空行分隔开

FishC 发表于 2024-6-28 23:32:22

pallas 发表于 2024-06-28 23:31
import xlwings as xw
import pandas as pd
import...

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

### 完整的代码示例

import pandas as pd
import os

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

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

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

    return tables

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

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

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

    merged_table = merge_tables(all_tables)

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

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

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

main(input_files, output_file)

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

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

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

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

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

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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

pallas 发表于 2024-6-28 23:39:37

提取多个excel表中同一个sheet表中不同的小表格,将不同的小表格分别合并在一起,且用空行隔开,导出为新的excel

FishC 发表于 2024-6-28 23:40:08

pallas 发表于 2024-06-28 23:39
提取多个excel表中同一个sheet表中不同的小表格,将不 ...

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

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

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

import pandas as pd
import os

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

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

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

    return tables

def merge_tables(tables_list):
    merged_df = pd.DataFrame()
    for tables in tables_list:
      for table in tables:
            merged_df = pd.concat( * len(table.columns)])], ignore_index=True)
    return merged_df

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

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

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

input_files = # 这里替换为你的文件路径
output_file = r'path_to_output.xlsx'# 这里替换为你的输出文件路径

main(input_files, output_file)

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

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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

pallas 发表于 2024-6-28 23:50:21

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

生成表格的第一行有Unnamed: 1,如何不让其生成

FishC 发表于 2024-6-28 23:50:41

pallas 发表于 2024-06-28 23:50
生成表格的第一行有Unnamed: 1,如何不让其生成

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

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

import pandas as pd
import os

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

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

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

    return tables

# 合并表格,并用空行隔开
def merge_tables(tables):
    merged_df = pd.DataFrame()
    for table in tables:
      if not merged_df.empty:
            merged_df = pd.concat(]), table], ignore_index=True)
      else:
            merged_df = table

    return merged_df

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

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

    merged_df = merge_tables(all_tables)

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

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

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 小助理,如未能正确解答您的问题,请继续追问。

pallas 发表于 2024-6-29 00:21:19

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

抬头要共用

FishC 发表于 2024-6-29 00:21:44

pallas 发表于 2024-06-29 00:21
抬头要共用

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

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

这是修正后的代码:

import pandas as pd
import os

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

    header = None

    # 分割逻辑:遇到空行就分割
    for _, row in df.iterrows():
      if row.isnull().all():# 判断空行
            if temp_df:
                if not header:
                  header = temp_df.index.tolist()
                table = pd.DataFrame(temp_df)
                tables.append(table)
                temp_df = []
      else:
            temp_df.append(row)

    if temp_df:
      if not header:
            header = temp_df.index.tolist()
      table = pd.DataFrame(temp_df)
      tables.append(table)

    return tables, header

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

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

    return merged_table

# 主函数
def main(input_files, output_file):
    all_tables = []
    common_header = None

    for file in input_files:
      tables, header = extract_tables_from_excel(file)
      if common_header is None:
            common_header = header
      tables = remove_last_two_rows(tables)
      all_tables.extend(tables)

    final_merged_table = merge_tables(all_tables, common_header)

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

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

main(input_files, output_file)

### 注意事项:

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

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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

pallas 发表于 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'?

FishC 发表于 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`列并保持相同的标题行,这里是修改后的完整代码:

import pandas as pd
import os

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

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

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

    return tables

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

    return merged_table

def main(input_files, output_file):
    all_tables = []
    common_header = None

    for file in input_files:
      tables = extract_tables_from_excel(file)
      if common_header is None and tables:
            common_header = tables.columns.tolist()
      all_tables.extend(tables)

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

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

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 小助理,如未能正确解答您的问题,请继续追问。
页: [1] 2
查看完整版本: python处理excel