feat: Add support for copying chartsheets with chart metadata

This commit is contained in:
Bobby Abellana (aider) 2025-02-13 14:24:16 -08:00
parent dfe99a9733
commit a850772b55

View File

@ -71,19 +71,51 @@ def copy_excel_file(source_path, destination_path, passwords):
for sheet_name in source_wb.sheetnames:
logging.debug(f"Copying sheet: {sheet_name}")
source_sheet = source_wb[sheet_name]
dest_sheet = dest_wb.create_sheet(title=sheet_name)
for row in source_sheet.iter_rows():
for cell in row:
dest_cell = dest_sheet.cell(row=cell.row, column=cell.column)
dest_cell.value = cell.value
if cell.has_style:
dest_cell.font = copy(cell.font)
dest_cell.border = copy(cell.border)
dest_cell.fill = copy(cell.fill)
dest_cell.number_format = cell.number_format
dest_cell.protection = copy(cell.protection)
dest_cell.alignment = copy(cell.alignment)
# Create new sheet in destination workbook
if source_sheet.sheet_type == 'chartsheet':
# For chartsheets, we need to create a worksheet instead
dest_sheet = dest_wb.create_sheet(title=sheet_name)
# Copy chart data if available
if hasattr(source_sheet, 'chart') and source_sheet.chart:
# Copy chart title if exists
if hasattr(source_sheet.chart, 'title') and source_sheet.chart.title:
dest_sheet['A1'] = f"Chart Title: {source_sheet.chart.title.text}"
# Copy chart series data if exists
if hasattr(source_sheet.chart, 'series'):
row = 2
for idx, series in enumerate(source_sheet.chart.series, 1):
# Write series title/name
if hasattr(series, 'title'):
dest_sheet.cell(row=row, column=1, value=f"Series {idx}: {series.title}")
# Try to get values if available
if hasattr(series, 'values'):
try:
for col, value in enumerate(series.values, 2):
dest_sheet.cell(row=row, column=col, value=value)
except:
pass # Skip if values can't be accessed
row += 1
else:
# Regular worksheet handling
dest_sheet = dest_wb.create_sheet(title=sheet_name)
# Copy cell contents and styles
for row in source_sheet.iter_rows():
for cell in row:
dest_cell = dest_sheet.cell(row=cell.row, column=cell.column)
dest_cell.value = cell.value
if cell.has_style:
dest_cell.font = copy(cell.font)
dest_cell.border = copy(cell.border)
dest_cell.fill = copy(cell.fill)
dest_cell.number_format = cell.number_format
dest_cell.protection = copy(cell.protection)
dest_cell.alignment = copy(cell.alignment)
os.makedirs(os.path.dirname(destination_path), exist_ok=True)
logging.debug(f"Destination directory ensured: {os.path.dirname(destination_path)}")