如何在Python中将多个Excel文件合并到一张工作表中并保持文件的格式?

问题描述 投票:0回答:1

我的目标是将多个Excel文件合并为一张数据,并且在新文件中仍然保留已合并文件的格式。我尝试了使用 Pandas 和 openpyxl 的解决方法,但现在只有第一个文件获得正确的格式,然后将其余文件合并而不进行格式化。这是我当前的代码:

df = pd.DataFrame()
for root, dir, filenames in os.walk(dir_containing_files):
    for file in filenames:
        file_path = os.path.abspath(os.path.join(root, file))
        if file.endswith('.xlsx'):
            df = df.append(pd.read_excel(file_path), ignore_index=True) 
 
wb = Workbook()
ws = wb.active

for r in dataframe_to_rows(df, index=True, header=True):
    ws.append(r)

source_wb = load_workbook(file_path)
source_sheet = source_wb.active

for row in source_sheet.rows:
    for cell in row:
        # Read and assign formatting to new file
        new_cell = ws.cell(row=cell.row, column=cell.column,
            value= cell.value)
        if cell.has_style:
            new_cell.font = copy(cell.font)
            new_cell.border = copy(cell.border)
            new_cell.fill = copy(cell.fill)
            new_cell.number_format = copy(cell.number_format)
            new_cell.protection = copy(cell.protection)
            new_cell.alignment = copy(cell.alignment)


wb.save('merge.xlsx')
print('merge complete')
python excel pandas openpyxl
1个回答
0
投票

我已经使用 openpyxl 3.1.2 进入我想要合并的每个文件并使用变量 row_number 跟踪行来完成此操作

def merge_delete_files(number_of_files): # 创建一个新的工作簿来存储合并后的数据 merged_wb = openpyxl.Workbook() merged_ws = merged_wb.active

excel_files = []

# Create the list of files
for i in range(int(number_of_files)):
    excel_files.append("Excels_folder/smaller_file_" + str(i + 1) + ".xlsx")

# Specify the destination sheet in the merged workbook
destination_sheet = merged_wb.active

row_number = 0
# Loop through each Excel file to merge
for file_path in excel_files:
    # Open the source workbook
    source_wb = openpyxl.load_workbook(file_path)

    # Select the desired sheet from the source workbook
    source_sheet = source_wb.active

    # Loop through rows and cells in the source sheet
    for row in source_sheet.iter_rows():
        row_number += 1
        for cell in row:
            # Write the cell value in the destination sheet keeping the source formatting
            string = cell.column_letter + str(row_number)
            destination_sheet[string].value = cell.value
            destination_sheet[string].font = copy(cell.font)
            destination_sheet[string].alignment = copy(cell.alignment)
            destination_sheet[string].number_format = copy(cell.number_format)
            destination_sheet[string].protection = copy(cell.protection)
            destination_sheet[string].fill = copy(cell.fill)
            destination_sheet[string].border = copy(cell.border)

# Save the merged workbook to a file
merged_wb.save('merged.xlsx')

print('Excel files merged successfully.')
© www.soinside.com 2019 - 2024. All rights reserved.