Implemented direct XML modification approach to replace {store_name} in all formulas including ArrayFormulas

This commit is contained in:
denisacirstea
2025-09-12 12:12:40 +03:00
parent 8080e69fca
commit 41d7b9c755
2 changed files with 213 additions and 5 deletions

79
direct_xml_update.py Normal file
View File

@@ -0,0 +1,79 @@
#!/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
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'):
# 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