From 3fda676a47416870a52680c78294daeff05058a5 Mon Sep 17 00:00:00 2001 From: denisacirstea Date: Fri, 12 Sep 2025 12:46:23 +0300 Subject: [PATCH] Simplified code by integrating direct_xml functionality into update_excel.py and removing re-applying of variables --- direct_xml_update.py | 86 ------------------------------ update_excel.py | 124 +++++++++++++++++++++++++++---------------- 2 files changed, 79 insertions(+), 131 deletions(-) delete mode 100644 direct_xml_update.py diff --git a/direct_xml_update.py b/direct_xml_update.py deleted file mode 100644 index bbc7bd6..0000000 --- a/direct_xml_update.py +++ /dev/null @@ -1,86 +0,0 @@ -#!/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 diff --git a/update_excel.py b/update_excel.py index 9a39e42..427486f 100755 --- a/update_excel.py +++ b/update_excel.py @@ -4,7 +4,7 @@ import os import re import openpyxl from openpyxl.utils import get_column_letter -from direct_xml_update import update_excel_with_direct_xml +from zipfile import ZipFile, ZIP_DEFLATED def update_excel_variables(excel_path): """ @@ -107,9 +107,9 @@ def update_excel_variables(excel_path): print(f"Updated {cell_ref} with value: {value}") except Exception as e: print(f"Error updating cell {cell_ref}: {e}") - - # Save the workbook immediately after updating the cells - print("Saving workbook after updating variables...") + + # Save the workbook with variables updated + print("Saving workbook with updated variables...") wb.save(excel_path) # Update sheet names - replace {store_name} with actual store name @@ -131,40 +131,13 @@ def update_excel_variables(excel_path): sheet_name_mapping[sheet_name] = new_sheet_name print(f"Renamed sheet '{sheet_name}' to '{new_sheet_name}'") - # Use direct XML modification to replace all instances of {store_name} - print("Using direct XML modification to update all formulas...") - modified_file = update_excel_with_direct_xml(excel_path, store_name) + # Save the workbook with renamed sheets + wb.save(excel_path) - if modified_file and os.path.exists(modified_file): - # Use the modified file instead of the original - print(f"Using modified file: {modified_file}") - # Copy the modified file back to the original location - import shutil - shutil.copy2(modified_file, excel_path) - # Remove the modified file - os.remove(modified_file) - # Reload the workbook to get the changes - wb = openpyxl.load_workbook(excel_path) - - # Re-apply the variables to make sure they weren't overwritten - print("Re-applying variables after XML modification...") - try: - sheet = wb['Variables'] - for cell_ref, value in cell_mappings.items(): - try: - cell = sheet[cell_ref] - cell.value = value - print(f"Re-applied {cell_ref} with value: {value}") - except Exception as e: - print(f"Error re-applying cell {cell_ref}: {e}") - - # Save the workbook again - wb.save(excel_path) - except Exception as e: - print(f"Error re-applying variables: {e}") + # Use direct XML modification to replace all instances of {store_name} in formulas + print("Using direct XML modification to update all formulas...") + update_excel_with_direct_xml(excel_path, store_name) - # Save the workbook - wb.save(excel_path) print(f"Excel file updated successfully: {excel_path}") return True @@ -172,19 +145,80 @@ def update_excel_variables(excel_path): print(f"Error updating Excel file: {e}") return False -def update_formula_references(workbook, sheet_name_mapping): +def update_excel_with_direct_xml(excel_path, store_name): """ - This function is no longer used directly - we now use direct_xml_update.py instead. - It's kept here for backward compatibility. + Update all references to {store_name} in the Excel file by directly modifying XML Args: - workbook: The openpyxl workbook object - sheet_name_mapping: Dictionary mapping old sheet names to new sheet names + excel_path: Path to the Excel file + store_name: The store name to replace {store_name} with + + Returns: + bool: True if successful, False otherwise """ - # This function is now just a placeholder - # The actual work is done by update_excel_with_direct_xml in direct_xml_update.py - print("Using direct XML modification approach instead of formula reference updating") - return 0 + try: + print(f"Using direct XML modification to replace '{{store_name}}' with '{store_name}'...") + + # Create a temporary file for modification + temp_dir = os.path.dirname(os.path.abspath(excel_path)) + temp_file = os.path.join(temp_dir, "_temp_for_xml_edit.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(excel_path, '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}") + return True + + except Exception as e: + print(f"Error updating Excel file with direct XML modification: {e}") + import traceback + traceback.print_exc() + return False if __name__ == "__main__": # For testing purposes