import os
import openpyxl
from openpyxl.styles import PatternFill
from collections import defaultdict
import shutil
# Function to copy a sheet with styles
def copy_sheet(source_sheet, target_sheet):
for row in source_sheet.iter_rows():
for cell in row:
new_cell = target_sheet.cell(row=cell.row, column=cell.col_idx, value=cell.value)
if cell.has_style:
new_cell._style = cell._style
target_sheet.sheet_format = source_sheet.sheet_format
target_sheet.merged_cells = source_sheet.merged_cells
# Function to get list of xlsx files in a directory (with subdirectories)
def get_all_xlsx_files(directory):
file_paths = []
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.xlsx') or file.endswith('.xlsm'):
file_paths.append(os.path.join(root, file))
return file_paths
# Function to ensure the output directory structure matches the target directory
def ensure_output_directory_structure(target_file_path, target_dir, output_dir):
relative_path = os.path.relpath(target_file_path, target_dir)
output_file_path = os.path.join(output_dir, relative_path)
os.makedirs(os.path.dirname(output_file_path), exist_ok=True)
return output_file_path
# Function to merge two workbooks
def merge_workbooks(source_file, target_file, output_file):
source_wb = openpyxl.load_workbook(source_file, data_only=False)
target_wb = openpyxl.load_workbook(target_file, data_only=False)
output_wb = openpyxl.Workbook()
# First, copy the first sheet from target to output
target_sheet_names = target_wb.sheetnames
source_sheet_names = source_wb.sheetnames
first_sheet_name = target_sheet_names[0]
target_first_sheet = target_wb[first_sheet_name]
output_first_sheet = output_wb.active
output_first_sheet.title = first_sheet_name
copy_sheet(target_first_sheet, output_first_sheet)
# Process other sheets
for sheet_name in target_sheet_names[1:]:
if sheet_name in source_sheet_names:
source_sheet = source_wb[sheet_name]
else:
# If sheet not in source, just copy it from target to output
target_sheet = target_wb[sheet_name]
output_sheet = output_wb.create_sheet(title=sheet_name)
copy_sheet(target_sheet, output_sheet)
continue
target_sheet = target_wb[sheet_name]
output_sheet = output_wb.create_sheet(title=sheet_name)
merge_sheets(source_sheet, target_sheet, output_sheet)
# Save the output workbook
output_wb.save(output_file)
# Function to merge two sheets
def merge_sheets(source_sheet, target_sheet, output_sheet):
source_max_row = source_sheet.max_row
target_max_row = target_sheet.max_row
# Define grey fill for new columns and rows
grey_fill = PatternFill(start_color='C0C0C0', end_color='C0C0C0', fill_type='solid')
current_row = 1
max_column = max(source_sheet.max_column, target_sheet.max_column)
# Copy description rows from target to output
while current_row <= target_max_row:
target_row = target_sheet[current_row]
# If the fourth cell has a value, it's the start of a data table
if target_row[3].value:
break
else:
# Copy the row to output sheet
for cell in target_row:
new_cell = output_sheet.cell(row=cell.row, column=cell.col_idx, value=cell.value)
if cell.has_style:
new_cell._style = cell._style
current_row += 1
# Now process data tables in the target sheet
while current_row <= target_max_row:
# Check if this row starts a data table
target_row = target_sheet[current_row]
if target_row[3].value:
# Start of a data table
table_start_row = current_row
# Get target table information
target_table_info = get_table_info(target_sheet, current_row)
# Find the corresponding table in source sheet
source_table_info = find_matching_table_in_source(source_sheet, target_table_info['table_name'])
if source_table_info:
# Merge the tables
merge_tables(source_table_info, target_table_info, output_sheet, grey_fill)
# Update current_row to skip over the data table that was just processed
current_row = target_table_info['end_row'] + 1
else:
# If no matching table in source, copy the table from target to output
copy_table_to_output(target_sheet, output_sheet, table_start_row, target_table_info['end_row'])
current_row = target_table_info['end_row'] + 1
else:
# Empty or description row after data table, copy it
target_row = target_sheet[current_row]
for cell in target_row:
new_cell = output_sheet.cell(row=cell.row, column=cell.col_idx, value=cell.value)
if cell.has_style:
new_cell._style = cell._style
current_row += 1
# Function to get information about a data table in a sheet starting from a given row
def get_table_info(sheet, start_row):
table_info = {}
max_row = sheet.max_row
header_row = sheet[start_row]
table_name = header_row[3].value # Column D (index 3) is the table name
table_info['table_name'] = table_name
table_info['start_row'] = start_row
# Get headers
headers = []
header_styles = []
col_idx = 4 # Start from column E (index 4)
while True:
cell = header_row[col_idx]
if cell.value is not None and cell.value != '':
headers.append(cell.value)
if cell.has_style:
header_styles.append(cell._style)
else:
header_styles.append(None)
col_idx += 1
else:
break
table_info['headers'] = headers
table_info['header_styles'] = header_styles
# Get primary key indices
primary_key_indices = []
for idx, header in enumerate(headers):
if header.startswith('#'):
primary_key_indices.append(idx)
table_info['primary_key_indices'] = primary_key_indices
# Get data rows
data_rows = []
data_row_styles = []
data_row_idx = start_row + 1
while data_row_idx <= max_row:
data_row = sheet[data_row_idx]
if all(cell.value in (None, '') for cell in data_row):
# Empty row indicates end of data table
break
else:
row_values = []
row_styles = []
for col_idx in range(4, 4 + len(headers)):
cell = data_row[col_idx]
row_values.append(cell.value)
if cell.has_style:
row_styles.append(cell._style)
else:
row_styles.append(None)
data_rows.append(row_values)
data_row_styles.append(row_styles)
data_row_idx += 1
table_info['data_rows'] = data_rows
table_info['data_row_styles'] = data_row_styles
table_info['end_row'] = data_row_idx - 1
return table_info
# Function to find matching table in source sheet
def find_matching_table_in_source(source_sheet, table_name):
max_row = source_sheet.max_row
current_row = 1
while current_row <= max_row:
source_row = source_sheet[current_row]
if source_row[3].value == table_name:
# Found matching table
table_info = get_table_info(source_sheet, current_row)
return table_info
else:
current_row += 1
# Table not found
return None
# Function to merge two tables and write to output sheet
def merge_tables(source_table, target_table, output_sheet, grey_fill):
# Write header row
output_row_idx = output_sheet.max_row + 1
# Copy the first four cells from target header row
for col_idx in range(1, 5):
cell = output_sheet.cell(row=output_row_idx, column=col_idx, value=target_table['start_row'])
target_cell = target_sheet.cell(row=target_table['start_row'], column=col_idx)
if target_cell.has_style:
cell._style = target_cell._style
# Write headers
all_headers = target_table['headers'][:]
all_header_styles = target_table['header_styles'][:]
new_columns = []
for idx, header in enumerate(source_table['headers']):
if header not in target_table['headers']:
all_headers.append(header)
all_header_styles.append(source_table['header_styles'][idx])
new_columns.append(len(all_headers) - 1) # Index of new column
# Write headers to output
for idx, header in enumerate(all_headers):
cell = output_sheet.cell(row=output_row_idx, column=5 + idx, value=header)
if idx < len(target_table['headers']):
if target_table['header_styles'][idx]:
cell._style = target_table['header_styles'][idx]
else:
if idx - len(target_table['headers']) < len(source_table['header_styles']):
header_style = source_table['header_styles'][idx - len(target_table['headers'])]
if header_style:
cell._style = header_style
# Apply grey fill to new columns
cell.fill = grey_fill
# Build primary key index mapping
target_pk_map = {}
for idx, row in enumerate(target_table['data_rows']):
pk = tuple(row[i] for i in target_table['primary_key_indices'])
target_pk_map[pk] = idx
# Write data rows
data_rows = []
data_row_styles = []
for idx, row in enumerate(target_table['data_rows']):
full_row = row[:]
# Add empty values for new columns
full_row.extend([None] * len(new_columns))
data_rows.append(full_row)
data_row_styles.append(target_table['data_row_styles'][idx])
# Merge data from source
for idx, row in enumerate(source_table['data_rows']):
pk = tuple(row[i] for i in source_table['primary_key_indices'])
if pk not in target_pk_map:
# New row, add to data_rows
full_row = [None] * len(target_table['headers'])
# Map existing columns
for col_idx, header in enumerate(source_table['headers']):
if header in target_table['headers']:
target_col_idx = target_table['headers'].index(header)
full_row[target_col_idx] = row[col_idx]
else:
# New columns
target_col_idx = all_headers.index(header)
full_row[target_col_idx] = row[col_idx]
data_rows.append(full_row)
# Get styles
full_row_styles = [None] * len(target_table['headers'])
data_row_styles.append(full_row_styles)
# Write data rows to output
for row_idx, row in enumerate(data_rows):
output_row_idx += 1
for col_idx, value in enumerate(row):
cell = output_sheet.cell(row=output_row_idx, column=5 + col_idx, value=value)
if row_idx < len(target_table['data_row_styles']):
# Existing data row from target
style_list = data_row_styles[row_idx]
if col_idx < len(style_list) and style_list[col_idx]:
cell._style = style_list[col_idx]
if col_idx >= len(target_table['headers']):
# New columns in existing rows, apply grey fill
cell.fill = grey_fill
else:
# New data row from source
if row_idx - len(target_table['data_row_styles']) < len(source_table['data_row_styles']):
source_style_list = source_table['data_row_styles'][row_idx - len(target_table['data_row_styles'])]
if col_idx < len(source_style_list) and source_style_list[col_idx]:
cell._style = source_style_list[col_idx]
if col_idx >= len(target_table['headers']):
# New columns, apply grey fill
cell.fill = grey_fill
else:
# New row, apply grey fill to entire row
cell.fill = grey_fill
# Add an empty row at the end
output_sheet.append([])
# Function to copy a table from target to output sheet
def copy_table_to_output(target_sheet, output_sheet, start_row, end_row):
for row_idx in range(start_row, end_row + 1):
target_row = target_sheet[row_idx]
output_row_idx = output_sheet.max_row + 1
for cell in target_row:
new_cell = output_sheet.cell(row=output_row_idx, column=cell.col_idx, value=cell.value)
if cell.has_style:
new_cell._style = cell._style
# Add an empty row at the end
output_sheet.append([])
# Main function
def main():
# Directories
source_dir = 'path_to_source'
target_dir = 'path_to_target'
output_dir = 'path_to_output'
# Get list of target files
target_files = get_all_xlsx_files(target_dir)
for target_file in target_files:
relative_path = os.path.relpath(target_file, target_dir)
source_file = os.path.join(source_dir, relative_path)
output_file = os.path.join(output_dir, relative_path)
# Ensure output directory exists
os.makedirs(os.path.dirname(output_file), exist_ok=True)
if os.path.exists(source_file):
# Merge the workbooks
merge_workbooks(source_file, target_file, output_file)
else:
# If source file doesn't exist, copy target file to output directory
shutil.copy2(target_file, output_file)
if __name__ == '__main__':
main()
Explanation:
- copy_sheet: Copies an entire sheet from the source to the target, including cell values and styles.
- get_all_xlsx_files: Recursively gets all
.xlsx and .xlsm files from a directory.
- ensure_output_directory_structure: Ensures the output directory structure matches the target directory.
- merge_workbooks: Main function that merges two workbooks (source and target) and saves the merged workbook to the output file.
- merge_sheets: Merges individual sheets from source and target, following the specified rules.
- get_table_info: Extracts information about a table in a sheet, including headers, data rows, and styles.
- find_matching_table_in_source: Finds a matching table in the source sheet based on the table name.
- merge_tables: Merges two tables (from source and target), adds new columns and rows as necessary, and applies grey background fill to new data.
- copy_table_to_output: Copies a table from the target sheet to the output sheet without merging.
- main: Entry point of the script. Processes all matching files in the source and target directories.
Implementation Details:
- The script reads all Excel files from the target directory and checks if a matching file exists in the source directory.
- For each matching pair of files, it merges the workbooks according to the specified rules.
- The first sheet is copied as-is from the target to the output workbook.
- For other sheets, it merges data tables with matching table names (based on the "表" column).
- It identifies new columns and rows in the source that are not in the target and appends them to the output.
- New columns and rows are filled with a grey background to distinguish them.
- It preserves the styles from both the source and target workbooks.
- The merged workbook is saved to the output directory, maintaining the same directory structure and file names as the target.
Note:
- Replace
'path_to_source', 'path_to_target', and 'path_to_output' with the actual paths to your directories.
- Ensure that you have the
openpyxl library installed (pip install openpyxl).
- The script assumes that the data tables are separated by completely empty rows.
- The script processes only
.xlsx and .xlsm files.
- The script focuses on correctness and clarity, ensuring that the merging rules are followed precisely.
Please adjust the paths and test the script with your data. If any adjustments are needed based on the specifics of your data files, consider refining the functions accordingly.