鱼C论坛

 找回密码
 立即注册
楼主: pallas

python读取excel中单个sheet表内的多个表

[复制链接]
 楼主| 发表于 2024-6-22 15:00:21 | 显示全部楼层
合并多个excel表中的相同标题的的表,保留格式,输出excel,不同表之间以空行分隔
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-22 15:07:46 | 显示全部楼层
FishC 发表于 2024-6-22 14:23
好的,看来你的问题是关于一个异常:`OSError: File contains no valid workbook part`。这个错误通常 ...

合并多个excel表中的相同标题的的表,保留格式,输出excel,不同表之间以空行分隔
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-22 15:08:09 | 显示全部楼层
pallas 发表于 2024-06-22 15:07
合并多个excel表中的相同标题的的表,保留格式,输出e ...


合并多个Excel表中的相同标题的表格,并保留格式、在不同表之间以空行分隔,这确实是个有趣的小挑战。我们可以使用 `openpyxl` 库来实现这个任务,因为它支持对 Excel 文件进行复杂的读写操作,包括保留格式。

下面是一个完整的示例代码,它会读取多个Excel文件中的表格,合并它们,然后输出到一个新的Excel文件。每个表格之间用一行空行进行分隔。
import openpyxl
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
import pandas as pd
import glob

# 函数:获取所有Excel文件路径
def get_excel_files(directory_path):
    return glob.glob(directory_path + "/*.xlsx")

# 函数:读取单个Excel文件中的数据
def read_excel_data(file_path):
    data_frames = 
    workbook = openpyxl.load_workbook(file_path)
    
    # 假设只读取第一个sheet
    sheet = workbook.active
    data = sheet.values
    columns = next(data)  # 获取表头
    
    # 读取整个sheet的数据
    df = pd.DataFrame(data, columns=columns)
    
    return df

# 创建一个新的工作簿
output_wb = Workbook()
output_ws = output_wb.active
output_ws.title = "Merged Data"

# 目录路径(包含多个Excel文件)
directory_path = r"D:\Path\To\Your\Directory"
excel_files = get_excel_files(directory_path)

# 合并数据
for file_path in excel_files:
    print(f"处理文件:{file_path}")
    df = read_excel_data(file_path)

    # 将数据框内容写入工作表
    for r_idx, row in enumerate(dataframe_to_rows(df, index=False, header=True), 1):
        for c_idx, value in enumerate(row, 1):
            cell = output_ws.cell(row=output_ws.max_row + 1, column=c_idx, value=value)
            cell.style = 'Normal'  # 保留格式,可根据需要调整

    # 插入一行空行
    output_ws.append()

# 保存新的Excel文件
output_file = r"D:\Path\To\Your\Directory\merged_output.xlsx"
output_wb.save(output_file)
print(f"合并完成,保存为:{output_file}")

### 解释下代码:
1. **读取文件路径**:`get_excel_files` 函数获取目录下所有的 `.xlsx` 文件。
2. **读取Excel数据**:`read_excel_data` 函数从每个Excel文件中读取数据,并将其转换为Pandas数据框。
3. **创建新工作簿**:`output_wb` 是新创建的Excel工作簿,将所有数据合并到这个工作簿中。
4. **合并数据**:遍历所有的Excel文件,将每个文件中的数据写入新的工作簿,并在每个表格之间插入空行。
5. **保存新的Excel文件**:最终将所有合并后的数据保存到新的Excel文件中。

### 保留格式
示例代码中的`cell.style = 'Normal'`可以根据需要调整。如果您有更复杂的格式需求,可能需要手动设置单元格的样式。

### 注意事项
1. 如果你有多个sheet需要合并,可以调整读取和写入逻辑来适应这个需求。
2. 数据量较大时,性能可能会有所影响,可以根据实际情况进行优化。

希望这段代码对你有帮助,如果有任何疑问或者需要进一步的功能,欢迎继续交流!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-25 18:33:42 | 显示全部楼层
FishC 发表于 2024-6-22 15:08
合并多个Excel表中的相同标题的表格,并保留格式、在不同表之间以空行分隔,这确实是个有趣的小挑战。 ...

将同一个excel中,同一个sheet中多个表格保留第一个表的标题,合并其他的表
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-25 18:34:09 | 显示全部楼层
pallas 发表于 2024-06-25 18:33
将同一个excel中,同一个sheet中多个表格保留第一个表 ...


理解了,你的需求是将同一个Excel文件中的单个Sheet表内的多个表格合并,保留第一个表的标题,而其他表的标题则去掉,同时在合并后的表格之间插入空行。这个过程需要操作单元格数据和格式。我们可以用 `openpyxl` 这个库来完成。

下面是一个示例代码,可以帮助你实现这一目标:
import openpyxl
from openpyxl import Workbook
from copy import copy

def merge_tables(src_file, dest_file, sheet_name):
    # 打开源Excel文件
    wb = openpyxl.load_workbook(src_file)
    sheet = wb[sheet_name]

    # 创建一个新的Workbook用于保存合并后的结果
    new_wb = Workbook()
    new_sheet = new_wb.active
    
    # 初始化变量
    current_row = 1
    table_start_row = None
    headers = None

    # 遍历行,找到每个表格的开始并合并
    for row in sheet.iter_rows(values_only=False):
        if row[0].value is not None and (table_start_row is None or (sheet.row_dimensions[row[0].row].hidden)):
            if table_start_row is not None:
                # 复制上一个表格内容(跳过第一行)
                for r in range(table_start_row + 1, row[0].row):
                    for c in range(1, sheet.max_column + 1):
                        new_cell = new_sheet.cell(row=current_row, column=c, value=sheet.cell(row=r, column=c).value)
                        
                        # 复制格式
                        if sheet.cell(row=r, column=c).has_style:
                            new_cell.font = copy(sheet.cell(row=r, column=c).font)
                            new_cell.border = copy(sheet.cell(row=r, column=c).border)
                            new_cell.fill = copy(sheet.cell(row=r, column=c).fill)
                            new_cell.number_format = copy(sheet.cell(row=r, column=c).number_format)
                            new_cell.protection = copy(sheet.cell(row=r, column=c).protection)
                            new_cell.alignment = copy(sheet.cell(row=r, column=c).alignment)

                    current_row += 1

                # 在两个表格之间插入空行
                current_row += 1

            table_start_row = row[0].row
            if headers is None:
                # 复制标题行
                headers = [cell.value for cell in row]
                for idx, header in enumerate(headers, start=1):
                    new_sheet.cell(row=1, column=idx, value=header)
                current_row += 1

    # 复制最后一个表格内容(跳过第一行)
    for r in range(table_start_row + 1, sheet.max_row + 1):
        for c in range(1, sheet.max_column + 1):
            new_cell = new_sheet.cell(row=current_row, column=c, value=sheet.cell(row=r, column=c).value)
            
            # 复制格式
            if sheet.cell(row=r, column=c).has_style:
                new_cell.font = copy(sheet.cell(row=r, column=c).font)
                new_cell.border = copy(sheet.cell(row=r, column=c).border)
                new_cell.fill = copy(sheet.cell(row=r, column=c).fill)
                new_cell.number_format = copy(sheet.cell(row=r, column=c).number_format)
                new_cell.protection = copy(sheet.cell(row=r, column=c).protection)
                new_cell.alignment = copy(sheet.cell(row=r, column=c).alignment)
        
        current_row += 1

    # 保存新文件
    new_wb.save(dest_file)

# 使用示例
src_file = "your_excel_file.xlsx"
dest_file = "merged_excel_file.xlsx"
sheet_name = "Sheet1"

merge_tables(src_file, dest_file, sheet_name)

### 代码解释:
1. **导入必要的库**:使用 `openpyxl` 来操作Excel文件。
2. **打开源Excel文件并选择指定Sheet**。
3. **创建新的Workbook**:用于保存合并后的结果。
4. **遍历行**:找到每个表格的开始位置并进行合并:
   - 若当前行是新的表格的开始,且前面已经有一个表格的开始位置,则复制前一个表格内容(跳过第一行)。
   - 将两个表格之间插入空行。
   - 找到标题行,并保留它。
5. **复制最后一个表格内容**。
6. **保存合并后的新文件**。

希望这个例子能帮助你有效地合并单个Sheet中的多个表格并保留第一个表的标题。如果有任何进一步的问题,欢迎随时提问!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-25 18:41:33 | 显示全部楼层
FishC 发表于 2024-6-25 18:34
理解了,你的需求是将同一个Excel文件中的单个Sheet表内的多个表格合并,保留第一个表的标题,而其他表 ...

如果有多个excel同时执行这一操作呢
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-25 18:41:59 | 显示全部楼层
pallas 发表于 2024-06-25 18:41
如果有多个excel同时执行这一操作呢


明白了!你是想在多个Excel文件中执行合并操作,保留每个Sheet中第一个表格的标题,并合并其余的表。不同表格之间需要空行分隔。

下面,我将为你提供一个Python脚本,使用 `openpyxl` 库来操作Excel文件。如果还没有安装,可以通过以下命令来安装:
pip install openpyxl

以下是完整的代码:
import openpyxl
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
import glob

# 获取所有Excel文件的路径
file_paths = glob.glob('path_to_your_excel_files/*.xlsx')

# 创建一个新的工作簿
output_wb = Workbook()
output_ws = output_wb.active

# Function to copy cell with style
def copy_cell(src_cell, dst_cell):
    dst_cell.value = src_cell.value
    if src_cell.has_style:
        dst_cell.font = src_cell.font
        dst_cell.border = src_cell.border
        dst_cell.fill = src_cell.fill
        dst_cell.number_format = src_cell.number_format
        dst_cell.protection = src_cell.protection
        dst_cell.alignment = src_cell.alignment

# 定义一个全局行计数器
output_row = 1

for file_path in file_paths:
    # 打开Excel文件
    wb = openpyxl.load_workbook(file_path)
    
    # 假设我们只处理第一张Sheet表
    ws = wb.active
    
    # 初始变量
    first_table = True
    row_iter = ws.iter_rows()
    header_copied = False

    while True:
        try:
            row = next(row_iter)
            
            # 如果是第一个表格,将其标题行拷贝到输出文件
            if first_table and not header_copied:
                for col_num, cell in enumerate(row, 1):
                    copy_cell(cell, output_ws.cell(row=output_row, column=col_num))
                header_copied = True
                output_row += 1
                continue

            # 如果遇到空行,视为表格间的分割
            if all(cell.value is None for cell in row):
                first_table = False
                continue

            # 拷贝非标题行
            if not first_table:
                for col_num, cell in enumerate(row, 1):
                    copy_cell(cell, output_ws.cell(row=output_row, column=col_num))
                output_row += 1
        except StopIteration:
            break
            
    # 在不同表格间添加空行分隔
    output_row += 1

# 保存结果到新文件
output_wb.save('combined_output.xlsx')

### 代码解释:

1. **导入库**:我们使用 `openpyxl` 来操作Excel文件。
2. **获取文件路径**:使用 `glob` 模块获取目录下所有Excel文件的路径。
3. **创建输出工作簿**:我们创建一个新的工作簿,用于保存合并后的结果。
4. **定义一个函数来复制单元格及其格式**:这是为了确保在复制单元格时保留其样式。
5. **循环处理每个文件**:打开每个文件并处理它们的Sheet。
6. **复制标题和数据**:在每个Sheet中,如果是第一个表格,将其标题行复制到输出文件;对于后面的表格,仅复制数据行。
7. **添加空行分隔**:在不同表格间添加空行。

希望这段代码能帮助你完成任务。如果有任何问题或需要进一步解释,请告诉我!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-25 18:44:10 | 显示全部楼层
FishC 发表于 2024-6-25 18:41
明白了!你是想在多个Excel文件中执行合并操作,保留每个Sheet中第一个表格的标题,并合并其余的表。不 ...

要分别输出合并的excel
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-25 18:45:00 | 显示全部楼层
pallas 发表于 2024-06-25 18:44
要分别输出合并的excel


OK,了解了。你想要把同一个Excel文件中同一个Sheet内的多个表格合并,保留第一个表的标题,合并其他的表,并且对多个Excel文件执行相同的操作。合并后的数据分别输出为不同的Excel文件。

具体步骤如下:

1. **读取Excel文件**:读取每个Excel文件中的Sheet内容。
2. **识别多个表格**:找到Sheet中多个表格的分界点。
3. **合并表格**:保留第一个表格的标题,合并其他的表格内容。
4. **保存结果**:将合并后的内容保存为新的Excel文件。

下面是一个示例Python代码,它使用`pandas`库来完成这个任务:
import pandas as pd

def merge_tables_in_sheet(file_path, sheet_name):
    # 读取Excel文件中的指定Sheet
    df = pd.read_excel(file_path, sheet_name=sheet_name)
    
    # 假设每个表格之间有空行
    # 找到空行的索引
    empty_row_indices = df.index[df.isnull().all(axis=1)].tolist()
    
    # 根据空行索引,将表格分段
    table_indices = [0] + [idx + 1 for idx in empty_row_indices] + [len(df)]
    
    tables = []
    for start, end in zip(table_indices[:-1], table_indices[1:]):
        tables.append(df.iloc[start:end].dropna(how='all'))
    
    # 保留第一个表的标题,合并其他表
    header = tables[0].columns
    merged_df = pd.concat([table.iloc[1:] for table in tables], ignore_index=True)
    merged_df.columns = header
    
    return merged_df

def process_multiple_excel_files(file_paths, sheet_name):
    for file_path in file_paths:
        merged_df = merge_tables_in_sheet(file_path, sheet_name)
        output_path = file_path.replace('.xlsx', '_merged.xlsx')
        merged_df.to_excel(output_path, index=False)
        print(f"Processed {file_path}, saved merged table to {output_path}")

# 示例文件列表
excel_files = ['file1.xlsx', 'file2.xlsx', 'file3.xlsx']
sheet_name = 'Sheet1'

process_multiple_excel_files(excel_files, sheet_name)

### 代码解释:

1. **merge_tables_in_sheet函数**:
   - 读取指定Excel文件的Sheet内容。
   - 通过寻找空行的索引来识别多个表格。
   - 根据这些空行分段,每段数据表示一个表格。
   - 保留第一个表格的标题,合并其余表格的内容。
   - 返回合并后的DataFrame。

2. **process_multiple_excel_files函数**:
   - 遍历文件路径列表,对每个Excel文件执行`merge_tables_in_sheet`操作。
   - 将合并后的DataFrame保存为新的Excel文件,文件名为原文件名加上"_merged"后缀。

### 提示:
- 在实际应用中,表格之间的分隔可能不仅仅是空行,可能需要根据实际情况调整识别表格的逻辑。
- 可以通过传递额外的参数,使代码更通用和灵活。
  
这样一来,你就可以批量处理多个Excel文件中的Sheet,并将合并后的数据分别保存为新的Excel文件了。希望这个解释对你有帮助!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-26 20:08:30 | 显示全部楼层
合并一个sheet表中多个小表格,共用一个标题,且每个小表格都删除最后两行
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-26 20:10:07 | 显示全部楼层
pallas 发表于 2024-06-26 20:08
合并一个sheet表中多个小表格,共用一个标题,且每个 ...


明白了,你想要合并同一个Sheet中多个小表格,并删除每个小表格的最后两行,保留第一个表格的标题。好吧,咱们来写点代码解决这个问题吧!这可是Python的拿手好戏!

你需要先安装`pandas`库,如果还没有安装的话,可以用如下命令安装:
pip install pandas openpyxl

好了,现在进入代码环节:
import pandas as pd
import numpy as np

def combine_excel_sheets(input_file, output_file):
    # 读入 Excel 文件
    df = pd.read_excel(input_file, sheet_name=None)  # 读取整个文件中的所有sheet
    writer = pd.ExcelWriter(output_file, engine='xlsxwriter')  # 用于将数据写回Excel

    for sheet_name, sheet_df in df.items():  # 对每个sheet操作
        # 识别每个小表格,并将其合并
        indices = np.where(sheet_df.isnull().all(axis=1))[0]
        tables = []
        start_idx = 0
        for end_idx in indices:
            if start_idx != end_idx:
                table = sheet_df.iloc[start_idx:end_idx]
                if not table.empty:
                    tables.append(table)
            start_idx = end_idx + 1

        # 如果文件末尾也有个小表格,没有被空行包围
        if start_idx < len(sheet_df):
            table = sheet_df.iloc[start_idx:]
            if not table.empty:
                tables.append(table)

        # 删除每个小表格的最后两行
        tables = [table.iloc[:-2] for table in tables]

        # 合并所有小表格
        combined_df = pd.concat(tables, ignore_index=True)

        # 保留第一个表格的标题
        combined_df.columns = tables[0].columns

        # 将合并后的数据写回新的sheet
        combined_df.to_excel(writer, sheet_name=sheet_name, index=False)

    # 保存到新的Excel文件
    writer.save()
    print(f"合并后的文件保存为: {output_file}")

# 使用示例
input_file = 'your_input_file.xlsx'  # 输入文件路径
output_file = 'your_output_file.xlsx'  # 输出文件路径
combine_excel_sheets(input_file, output_file)

右边是解释:
1. `combine_excel_sheets` 是主函数,接收输入和输出文件的路径。
2. 使用 `pd.read_excel` 读取整个Excel文件内容,用 `sheet_name=None` 参数获取所有Sheet。
3. 查找每个Sheet中的空行,在每个空行之间的数据被作为一个独立的小表格分开存储。
4. 删除每个小表格的最后两行。
5. 将处理后的小表格合并起来,并保留第一个表格的标题行。
6. 用 `pd.ExcelWriter` 将最终处理过的数据写回Excel文件的新Sheet中。

如此一来,就能完成你所描述的任务啦!希望这个回答对你有帮助,如果还有更多问题,尽管问吧~

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-26 20:11:12 | 显示全部楼层
FishC 发表于 2024-6-26 20:10
明白了,你想要合并同一个Sheet中多个小表格,并删除每个小表格的最后两行,保留第一个表格的标题。好 ...

序号要连续
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-26 20:11:32 | 显示全部楼层


好,理解你的需求了。我们可以使用 `pandas` 库来完成这个任务。首先,我们需要安装 `pandas` 和 `openpyxl` 这两个库。你可以通过以下命令安装:
pip install pandas openpyxl

接下来,我们编写代码来读取 Excel 文件中的一个 Sheet,并将其中的多个小表格合并,删除每个小表格的最后两行,并让序号连续。
import pandas as pd

# 读取Excel文件
file_path = 'your_excel_file.xlsx'  # 请替换成你的文件路径
sheet_name = 'Sheet1'  # 请替换成你的Sheet名字

# 加载整个Sheet
df = pd.read_excel(file_path, sheet_name=sheet_name)

# 找到标题行和空行,用于识别每个小表格
header_row = 0  # 假设第1行为标题行
split_indices = df[df.isnull().all(axis=1)].index.tolist()

start_idx = header_row + 1
tables = []

for split_idx in split_indices:
    table = df.iloc[start_idx:split_idx - 2]  # 删除最后两行
    table.columns = df.iloc[header_row]  # 添加标题
    tables.append(table)
    start_idx = split_idx + 1

# 如果最后一个表格结束不是空行,需要手动添加最后一个表格
if start_idx < len(df):
    table = df.iloc[start_idx:-2]  # 删除最后两行
    table.columns = df.iloc[header_row]
    tables.append(table)

# 合并所有小表格
merged_df = pd.concat(tables, ignore_index=True)

# 处理序号连续
merged_df.reset_index(drop=True, inplace=True)
merged_df.index += 1  # 设置序号从1开始
merged_df.reset_index(inplace=True)
merged_df.rename(columns={'index': '序号'}, inplace=True)

# 输出合并后的表格到新的Excel文件
output_file_path = 'merged_output.xlsx'
merged_df.to_excel(output_file_path, index=False)

print(f"合并后的表格已保存至 {output_file_path}")

几点说明:

1. `header_row`:假设第1行为标题行。如果你的标题行在其他位置,请修改此值。
2. `split_indices`:找出空行的位置,用于拆分多个小表格。
3. 每个小表格去掉最后两行,并保留标题。
4. 使用 `pd.concat()` 向上合并所有小表格。
5. 重置索引确保序号连续并从1开始。
6. 最后输出合并后的表格到新的 Excel 文件。

希望这段代码能帮到你!如果有任何问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-26 20:15:52 | 显示全部楼层

合并一个sheet表中多个小表格,共用一个标题,且每个小表格都删除最后两行,序号要连续
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-26 20:16:20 | 显示全部楼层
pallas 发表于 2024-06-26 20:15
合并一个sheet表中多个小表格,共用一个标题,且每个 ...


好的,我们可以使用 Python 的 `pandas` 库来完成这个任务。以下是一个实现此功能的示例代码:
import pandas as pd

# 读取Excel文件中的特定Sheet
file_path = '你的Excel文件路径.xlsx'
sheet_name = 'Sheet1'
df = pd.read_excel(file_path, sheet_name=sheet_name)

# 假设每个小表格之间有一行或多行空行
# 识别每个小表格的起始和终止行
table_start_indices = df[df.iloc[:, 0].notna()].index
tables = []

for i, start_idx in enumerate(table_start_indices):
    if i < len(table_start_indices) - 1:
        end_idx = table_start_indices[i+1]
    else:
        end_idx = len(df)
    table = df.iloc[start_idx:end_idx]
    tables.append(table)

# 合并所有小表格,删除每个表格的最后两行
combined_df = pd.DataFrame()
header = tables[0].iloc[0]  # 第一个表格的标题

for table in tables:
    table = table.iloc[1:-2]  # 删除表格的最后两行,并保留除标题外的其他行
    combined_df = pd.concat([combined_df, table])

# 重置索引并重新添加标题
combined_df.columns = header
combined_df.reset_index(drop=True, inplace=True)
combined_df.insert(0, '序号', range(1, len(combined_df) + 1))

# 输出合并后的表格
print(combined_df)

# 保存到新的Excel文件
combined_df.to_excel('合并后的Excel文件.xlsx', index=False)

### 代码说明:

1. **读取Excel文件**:使用 `pd.read_excel` 读取指定Sheet的内容。
2. **识别小表格**:通过检查第一列非空值来确定每个小表格的起始行。
3. **提取和处理小表格**:遍历每个小表格,删除最后两行,并将所有小表格合并。
4. **添加序号**:重置索引并添加连续的序号。
5. **保存结果**:将合并后的数据框保存到新的Excel文件中。

你可以根据实际情况调整此代码,比如处理表格之间的间隔行数等。希望这个方法能解决你的问题!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-26 20:17:59 | 显示全部楼层
FishC 发表于 2024-6-26 20:16
好的,我们可以使用 Python 的 `pandas` 库来完成这个任务。以下是一个实现此功能的示例代码:

Traceback (most recent call last):
  File "D:\PyCharm\excel_merge\excel_merge\.venv\Lib\site-packages\finish_forth.py", line 32, in <module>
    combined_df.insert(0, '序号', range(1, len(combined_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
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-26 20:18:40 | 显示全部楼层
pallas 发表于 2024-06-26 20:17
Traceback (most recent call last):
  File "D:\PyC ...


你遇到的问题是因为你试图插入一个名为“序号”的列,而这个列已经存在于你的 DataFrame 中。为了避免这个错误,你可以在插入之前检查“序号”列是否已经存在,或者在插入之前删除现有的“序号”列。以下是更新后的代码示例:
import pandas as pd

# 读取 Excel 文件
file_path = 'path_to_your_excel_file.xlsx'
sheet_name = 'Sheet1'
df = pd.read_excel(file_path, sheet_name=sheet_name)

# 假设多个表格之间有一定的间隔,找到这些表格的开始位置
# 这里我们假设每个表格都有相同的标题行
header = list(df.columns)
start_indices = df.index[df.apply(lambda x: list(x) == header, axis=1)].tolist()

# 合并这些表格
merged_df = pd.DataFrame(columns=header)

for start_index in start_indices:
    temp_df = df.iloc[start_index+1:]  # 从标题行的下一行开始
    end_index = temp_df.index[temp_df.isnull().all(axis=1)].tolist()[0]  # 找到下一个空行的索引
    temp_df = temp_df.iloc[:end_index-2]  # 删除最后两行
    merged_df = pd.concat([merged_df, temp_df])

# 添加序号列
merged_df.reset_index(drop=True, inplace=True)
merged_df.insert(0, '序号', range(1, len(merged_df) + 1))

# 保存合并后的 DataFrame 到新的 Excel 文件
merged_df.to_excel('merged_output.xlsx', index=False)

print("合并完成!")

在这段代码中,我们:

1. 读取了 Excel 文件中的指定工作表。
2. 假设每个小表格之间有一定的间隔,并且每个小表格都有相同的标题行。
3. 找到每个小表格的开始位置(即标题行的位置)。
4. 合并这些小表格,并删除每个小表格的最后两行。
5. 为合并后的 DataFrame 添加连续的序号列。
6. 将合并后的 DataFrame 保存到新的 Excel 文件中。

请确保修改代码中的 `file_path` 和 `sheet_name` 为你自己的 Excel 文件路径和工作表名称。这样,你就可以按照你的需求合并多个小表格,并确保序号连续了。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-26 20:22:25 | 显示全部楼层
合并一个sheet表中多个小表格,共用一个标题,且每个小表格都删除最后两行,序号要连续,导出到新的excel表中
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-26 20:23:08 | 显示全部楼层
pallas 发表于 2024-06-26 20:22
合并一个sheet表中多个小表格,共用一个标题,且每个 ...


好的,我们可以使用 `pandas` 库来处理这个任务。以下是详细的代码示例,它将从单个 sheet 表中读取多个小表格,删除每个小表格的最后两行,合并这些小表格,并确保序号连续,然后将结果导出到新的 Excel 文件中。
import pandas as pd

# 读取Excel文件
file_path = 'path_to_your_excel_file.xlsx'
sheet_name = 'Sheet1'

# 读取整个sheet
df = pd.read_excel(file_path, sheet_name=sheet_name)

# 假设每个小表格之间有空行,可以用非空行标识每个小表格的开始
# 你可以根据实际情况修改条件,这里假设每个小表格都有相同的列名 "标题"

# 找到每个小表格的开始和结束行
starts = df[df.iloc[:, 0] == '标题'].index.tolist()
ends = starts[1:] + [len(df)]

# 存放每个小表格的DataFrame列表
df_list = []

for start, end in zip(starts, ends):
    sub_df = df.iloc[start:end, :]
    # 删除最后两行
    sub_df = sub_df.iloc[:-2, :]
    # 添加到列表中
    df_list.append(sub_df)

# 合并所有小表格
combined_df = pd.concat(df_list, ignore_index=True)

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

# 导出到新的Excel文件
output_file_path = 'combined_output.xlsx'
combined_df.to_excel(output_file_path, index=False)

print(f"合并后的表格已成功导出到 {output_file_path}")

### 代码说明:

1. **读取Excel文件**:使用 `pd.read_excel` 读取整个 sheet 表。
2. **找到每个小表格的开始和结束行**:通过查找标题行的位置,确定每个小表格的起始和结束位置。
3. **删除每个小表格的最后两行**:对于每个小表格,删除最后两行。
4. **合并所有小表格**:使用 `pd.concat` 合并所有小表格,并确保索引被忽略以使序号连续。
5. **添加序号列**:在合并后的 DataFrame 中插入一个连续的序号列。
6. **导出到新的Excel文件**:使用 `to_excel` 将最终的合并结果导出到新的 Excel 文件。

请确保你已经安装了 `pandas` 库,如果没有安装,可以使用 `pip install pandas` 命令来安装。修改代码中的 `file_path` 和 `sheet_name` 为你自己的 Excel 文件路径和 sheet 名称。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-6-26 20:26:07 | 显示全部楼层
合并一个sheet表中多个小表格,共用第一行,且每个小表格都删除最后两行,序号要连续,导出到新的excel表中
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-9-22 22:33

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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