this script doesnt update the ingredients at all, and the packaging updating is not 100%…
- User
this script doesnt update the ingredients at all, and the packaging updating is not 100% correct. please fix it.
import openpyxl from openpyxl import load_workbook import re from datetime import datetime import shutil
def find_matching_sheet(workbook, patterns): for sheet in workbook.sheetnames: for pattern in patterns: if re.search(pattern, sheet, re.IGNORECASE): return sheet return None
def identify_sheet_by_content(workbook, start_row, end_row): for sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] match_count = 0 for row in range(start_row, end_row + 1): if sheet.cell(row=row, column=1).value: match_count += 1 if match_count > (end_row - start_row) * 0.8: # 80% match threshold return sheet_name return None
def find_balance_column(sheet, is_fresh_pm): for col in sheet.iter_cols(min_row=2, max_row=2): header = col[0].value if header: header = str(header).lower() if is_fresh_pm: if "closing balance" in header: return col[0].column else: if "balance" in header: return col[0].column return None # If no matching column found
def process_sheet(sheet, is_fresh_pm): balance_column = find_balance_column(sheet, is_fresh_pm) if balance_column is None: print(f"Warning: Could not find balance column in {'Fresh PM' if is_fresh_pm else 'Ingredients'} sheet.") return {}
data = {} for row in sheet.iter_rows(min_row=3, values_only=True): material_code = row[0] # Column A balance = row[balance_column - 1] # balance_column is 1-based
codeif material_code and balance is not None: try: material_code = str(material_code).strip() balance = float(balance) data[material_code] = balance except (ValueError, TypeError): print(f"Warning: Non-numeric value '{balance}' found for material code '{material_code}'. Skipping.")return data
def update_balance_workbook(): try: current_stock_wb = load_workbook('current_stock.xlsx', data_only=True) except FileNotFoundError: print("Error: 'current_stock.xlsx' not found in the current directory.") return
Try to identify sheets by name
fresh_pm_sheet = find_matching_sheet(current_stock_wb, [r'fresh\s*pm', r'packaging']) ingredients_sheet = find_matching_sheet(current_stock_wb, [r'ingredients.*chemicals', r'chemicals.*ingredients'])
If name-based identification fails, try content-based identification
if not fresh_pm_sheet: fresh_pm_sheet = identify_sheet_by_content(current_stock_wb, 117, 150) if not ingredients_sheet: ingredients_sheet = identify_sheet_by_content(current_stock_wb, 1, 50)
- Assistant