#!/usr/bin/env python3 import os import re import openpyxl from zipfile import ZipFile, ZIP_DEFLATED def update_excel_with_direct_xml(excel_path, store_name): """ Update all references to {store_name} in the Excel file by directly modifying XML This function preserves all cell values and formulas that were previously set by the update_excel_variables function. Args: excel_path: Path to the Excel file store_name: The store name to replace {store_name} with Returns: str: Path to the modified Excel file """ try: print(f"Using direct XML modification to replace '{{store_name}}' with '{store_name}'...") # Save a copy of the original file to work with temp_dir = os.path.dirname(os.path.abspath(excel_path)) temp_file = os.path.join(temp_dir, "_temp_for_xml_edit.xlsx") modified_file = os.path.join(temp_dir, excel_path.replace('.xlsx', '_modified.xlsx')) # Make a copy of the original file import shutil shutil.copy2(excel_path, temp_file) # Count of replacements total_replacements = 0 # Process the Excel file with ZipFile(temp_file, 'r') as zip_in: with ZipFile(modified_file, 'w', ZIP_DEFLATED) as zip_out: # Process each file in the zip for item in zip_in.infolist(): content = zip_in.read(item.filename) # Only modify XML files that might contain formulas or text if item.filename.endswith('.xml'): # Skip sheet8.xml which is the Variables sheet (based on common Excel structure) if 'sheet8.xml' in item.filename: print(f"Skipping Variables sheet: {item.filename}") else: # Convert to string for text replacement try: text_content = content.decode('utf-8') # Check if this file contains our placeholder if '{store_name}' in text_content: # Count occurrences before replacement occurrences = text_content.count('{store_name}') total_replacements += occurrences # Replace all instances of {store_name} with the actual store name modified_content = text_content.replace('{store_name}', store_name) # Convert back to bytes content = modified_content.encode('utf-8') print(f"Replaced {occurrences} instances of '{{store_name}}' in {item.filename}") except UnicodeDecodeError: # Not a text file, leave as is pass # Write the file (original or modified) to the new zip zip_out.writestr(item, content) # Clean up the temporary file if os.path.exists(temp_file): os.remove(temp_file) print(f"Total replacements: {total_replacements}") print(f"Modified Excel file saved as: {modified_file}") return modified_file except Exception as e: print(f"Error updating Excel file: {e}") import traceback traceback.print_exc() return None