OEM ORDER LOADING & OVERALL REPORT AUTOMATION

Process Overview

Field Details
Process Name OEM Order Loading & Overall Report Automation
Segment REL – Relationship Business
Process Family Lenovo India
Process Users Wyzmindz Solutions Pvt Ltd
Process Purpose Two Python automations: (1) identifying new OEM Sales Orders from the client's order-loading file, matching them with AP Data and creating a standardized output; and (2) matching the Overall report with the OEM order-list base using Sales Order Number and generating a standardized output for the configured region and financial quarter.

Version History

Version Tag Prepared By Date of Update Validated By Reviewed By Approved By Revision Details
V 1.0 Sharanya J 13-10-2026 — Process Owner Process Manager Initial SOP for OEM Order Loading and Overall report automation

Distribution & Access List

Role Access / Responsibility
Analyst Run the scripts, confirm input files and validate outputs.
Team Lead Review output quality and investigate exceptions.
Process Manager Approve material changes to the process or reporting rules.

1.1 Purpose

The purpose of this SOP is to define the standard procedure for running the OEM Order Loading and Overall report automations. The scripts identify new Sales Orders that are not already present in the OEM base file, match eligible orders with AP Data, remove duplicate records and create structured Excel outputs. The second script matches Overall report records against the OEM order-list base and generates a standardized output for the configured financial quarter.

1.2 Scope

  • Process 1: OEM Order Loading and AP Data Processing.
  • Process 2: Overall report matching against the OEM order-list base.
  • Key matching field: Sales Order Number (Sales No / SO_No).
  • Output format: Excel workbook with a Final Output sheet.
  • The scripts do not directly update the OEM base workbook; they create output workbooks for review and further processing.

1.3 Business / Segment Overview

The OEM process supports the identification and consolidation of OEM-related Sales Orders for Lenovo India reporting. New orders received in the client's OEM Order Loading file are compared with the existing OEM order-list base to identify Sales Orders that are not already present. The new orders are then matched against AP Data to retrieve the associated End Customer Name and Business Model.

The Overall report automation identifies report rows whose SO_No exists in the OEM order-list base. It standardizes the matched records into Region, SalesOrder, MTM, Customer Name and FYQ fields. The output supports consistent OEM reporting and reduces manual matching work.

1.4 Responsibility and Authority

Role Responsibility
Analyst Receive and select the correct input files, run the scripts, check logs and validate output files.
Team Lead / Reviewer Review unmatched or unexpected records and confirm output quality.
Process Owner / Manager Approve changes to business rules, quarter settings or source-file structure.

1.5 Access Required

  • Access to the client OEM Order Loading file.
  • Access to the current OEM order-list base file.
  • Access to the latest AP Data file.
  • Access to the Overall report file for Process 2.
  • Read/write access to the configured OEM output folder.
  • Python environment with pandas, numpy, openpyxl and the appropriate Excel readers (pyxlsb for XLSB files; xlrd for XLS files).
  • Microsoft Excel for output review.

1.6 Overview of Tools

Tool / Library Purpose
Python Runs the automation scripts.
pandas Reads, cleans, filters, matches and deduplicates records.
NumPy Imported in the OEM script; not directly used in the current logic.
openpyxl Creates and formats the OEM output workbook and writes the Overall output.
pyxlsb / xlrd Reads XLSB / XLS input files where required.
Microsoft Excel Used to inspect source files and validate the generated outputs.

1.7 Dependencies

  • Input files must contain the expected column names exactly, apart from leading/trailing spaces where the script explicitly cleans them.
  • OEM Order Loading file must contain Sales No and End Customer Name.
  • OEM base file must contain Sales No and End Customer Name.
  • AP Data must contain Sales No, End Customer Name and Business Model, with the configured sheet name Data.
  • Overall report must contain SO_No, Material and Name of End Customer.
  • The file paths in each script must be updated to the correct current files before execution.
  • FYQ_VALUE in Process 2 must be updated when the reporting quarter changes.

1.8 Process Flow

Process 1 – OEM Order Loading and AP Data

Step Process Step
1 Start.
2 Read OEM Order Loading file — Load Sales No and End Customer Name.
3 Normalize and deduplicate — Trim spaces, standardize case and remove duplicate Sales No + customer combinations.
4 Read OEM base file — Build a set of existing Sales No values.
5 Identify new Sales Orders — Keep loading records whose normalized Sales No is not in the base.
6 Read AP Data — Load Sales No, End Customer Name and Business Model from the Data sheet.
7 Match new orders to AP Data — Match on normalized Sales No.
8 Remove duplicate output rows — Deduplicate on Sales No + End Customer Name + Business Model.
9 Create timestamped Excel output — Write the Final Output sheet with filters and frozen header row.
10 Validate and finish — Check the output and run summary.

Process 2 – Overall Report vs OEM Base

  1. Read OEM base file and Overall report.
  2. Trim column names and clean Sales No / SO_No values.
  3. Match Overall SO_No against OEM base Sales No using a left merge.
  4. Keep only matched records (equivalent to excluding #N/A results).
  5. Create output fields: Region, SalesOrder, MTM, Customer Name and FYQ.
  6. Save the timestamped Excel file and validate the matched records.

1.9 Steps of Procedure

A. OEM Order Loading and AP Data Processing

  1. Confirm that the client's OEM Order Loading file, current OEM order-list base and latest AP Data file are available.
  2. Open the first Python script and update LOADING_FILE, BASE_FILE, AP_DATA_FILE and OUTPUT_FOLDER to the correct file locations.
  3. Confirm that the input files contain the required columns: Sales No and End Customer Name in the loading and base files; Sales No, End Customer Name and Business Model in AP Data.
  4. Run the script. The script reads the loading file and standardizes Sales No and End Customer Name by trimming spaces, converting text to uppercase and normalizing repeated spaces.
  5. The script removes duplicate loading records based on the normalized combination of Sales No and End Customer Name.
  6. The script reads the OEM base and identifies Sales No values already present in the base file.
  7. The script keeps loading records whose Sales No is not already in the base. If no new orders are found, it logs a message and stops.
  8. The script reads the AP Data sheet named Data and matches the new Sales Orders against AP Data using normalized Sales No.
  9. If no AP Data matches are found, the script logs a message and stops. Otherwise, it keeps Sales No, End Customer Name and Business Model.
  10. The script removes duplicate final rows based on Sales No, End Customer Name and Business Model.
  11. The script creates a timestamped Excel file in the OEM output folder. The sheet is named Final Output and contains filters and a frozen header row.
  12. Review the run log and the generated output before using the records in the OEM order-list base.

B. Overall Report Matching Against OEM Base

  1. Confirm that the current OEM order-list base and the Overall report are available.
  2. Open the second Python script and update BASE_FILE, OVERALL_FILE and OUTPUT_FOLDER.
  3. Update FYQ_VALUE to the applicable financial quarter, for example FY2627Q3. Update REGION_VALUE only if the required reporting region changes.
  4. Run the script. It reads both workbooks and removes leading/trailing spaces from the column names.
  5. The script trims spaces from base Sales No and Overall SO_No, then matches Overall SO_No to base Sales No.
  6. Only matched records are retained; unmatched records equivalent to #N/A are excluded.
  7. The script creates the standardized output fields: Region, SalesOrder, MTM, Customer Name and FYQ.
  8. The output is saved as Overall_Base_Matched_<timestamp>.xlsx in the configured OEM output folder, with the sheet named Final Output.
  9. Open the output and validate the headers, quarter value and matched Sales Orders before using it.

1.10 Code Logic and Automation Details

Automation Logic
Input reading Reads Excel, XLSB or CSV files based on file extension in Process 1. Process 2 uses pandas Excel reading for configured workbooks.
Normalization Process 1 converts key values to uppercase, trims spaces and replaces repeated spaces before matching. Process 2 trims spaces but does not standardize case.
New-order identification Process 1 compares loading Sales No values with Sales No values from the OEM base.
AP matching Process 1 matches new orders to AP Data on normalized Sales No.
Deduplication Process 1 removes duplicate loading pairs and duplicate final combinations.
Overall matching Process 2 performs a left merge and keeps only rows with a match in the OEM base.
Output generation Both scripts create timestamped Excel outputs with a Final Output worksheet.

1.11 Output Overview

Output File Pattern Sheet Columns
Final_Output_<timestamp>.xlsx Final Output Sales No; End Customer Name; Business Model
Overall_Base_Matched_<timestamp>.xlsx Final Output Region; SalesOrder; MTM; Customer Name; FYQ

1.12 Validation Checklist

  • Confirm that the correct quarter's OEM base file is selected.
  • Confirm the loading file contains the expected Sales No and End Customer Name columns.
  • Confirm AP Data uses the expected Data sheet name and contains all required columns.
  • Review the script log for loading, base, new-order, matched and final record counts.
  • If no new orders or no AP matches are found, investigate the input files and key values before concluding the run.
  • Check that the first output contains only the three expected columns and has no duplicate combinations.
  • For the Overall output, confirm the Region and FYQ values are correct.
  • Verify that output records have matched against the OEM base and that the output file opens correctly.
  • Retain the source files and timestamped outputs according to the team's file-retention process.

1.13 Exception Handling

Issue Action
Required column missing Check the input file version and header spelling. Update the source or script only after confirming the intended schema.
AP Data sheet not found Confirm the sheet is named Data. The current script does not automatically handle DATA vs Data.
No new OEM orders found The script stops without creating a new output. Confirm whether all loading Sales Nos already exist in the base.
No AP matches found Check Sales No values, data availability and file versions. The current script stops without creating an output.
Incorrect quarter in output Update FYQ_VALUE in Process 2 and rerun the script.
Incorrect or stale source path Update the hard-coded file paths before running the script.
Unexpected match count Review source freshness, duplicate keys and differences in Sales Order formatting.

Important Technical Notes:

  • The first script checks whether Sales No exists in the base file; it does not use the customer name when deciding whether an order is already in the base.
  • The first script currently reads AP Data from a sheet named exactly Data. If the source sheet may be named DATA, the code needs a case-insensitive sheet-name adjustment.
  • The first script defines USE_CHUNKING and CHUNK_SIZE but does not currently use them.
  • The second script does not normalize letter case in Sales No / SO_No. If case differences occur in the source, matching rules may need to be strengthened.
  • The scripts create output workbooks only; they do not append results directly to the OEM base file.

Appendix A – OEM Order Loading Python Code

The following is the code supplied for Process 1. Update the configured paths and confirm the current source-file structure before execution.

"""
OEM Order Loading and AP Data Processing Automation - ADVANCED VERSION
Fully Corrected Version (No Summary Errors)
"""

import pandas as pd
import numpy as np
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
import os
from datetime import datetime
import gc


# ================= CONFIGURATION =================
USE_CHUNKING = False
CHUNK_SIZE = 100000
ENABLE_LOGGING = True
# =================================================


def log(message):
    if ENABLE_LOGGING:
        timestamp = datetime.now().strftime("%H:%M:%S")
        print(f"[{timestamp}] {message}")


def read_excel_optimized(file_path, sheet_name=0, usecols=None):

    _, ext = os.path.splitext(file_path)
    ext = ext.lower()

    if ext == ".xlsb":
        engine = "pyxlsb"
    elif ext == ".xls":
        engine = "xlrd"
    elif ext == ".csv":
        return pd.read_csv(file_path, usecols=usecols, dtype=str)
    else:
        engine = "openpyxl"

    return pd.read_excel(
        file_path,
        sheet_name=sheet_name,
        usecols=usecols,
        dtype=str,
        engine=engine
    )


def clean_and_normalize(df, column):
    return (
        df[column]
        .astype(str)
        .str.strip()
        .str.upper()
        .str.replace(r"\s+", " ", regex=True)
    )


def process_oem_orders_advanced(loading_file, base_file, ap_data_file, output_file):

    log("=" * 70)
    log("STEP 1: Reading OEM Order Loading file...")
    log("=" * 70)

    loading_df = read_excel_optimized(
        loading_file,
        usecols=["Sales No", "End Customer Name"]
    )

    log(f"✓ Loaded {len(loading_df):,} rows")

    loading_df["Sales No Clean"] = clean_and_normalize(loading_df, "Sales No")
    loading_df["Customer Clean"] = clean_and_normalize(loading_df, "End Customer Name")

    loading_df_unique = loading_df.drop_duplicates(
        subset=["Sales No Clean", "Customer Clean"]
    ).reset_index(drop=True)

    loading_count = len(loading_df_unique)

    log(f"✓ Unique records: {loading_count:,}")

    del loading_df
    gc.collect()

    # ================= BASE FILE =================
    log("\n" + "=" * 70)
    log("STEP 2: Reading OEM List base file...")
    log("=" * 70)

    base_df = read_excel_optimized(
        base_file,
        usecols=["Sales No", "End Customer Name"]
    )

    base_df["Sales No Clean"] = clean_and_normalize(base_df, "Sales No")
    base_sales_orders = set(base_df["Sales No Clean"])

    base_count = len(base_sales_orders)

    log(f"✓ Indexed {base_count:,} unique base Sales Nos")

    del base_df
    gc.collect()

    # ================= NEW ORDERS =================
    log("\n" + "=" * 70)
    log("STEP 3: Identifying new Sales Orders...")
    log("=" * 70)

    mask = ~loading_df_unique["Sales No Clean"].isin(base_sales_orders)

    new_orders = loading_df_unique[mask][
        ["Sales No", "End Customer Name", "Sales No Clean"]
    ].copy()

    new_orders_count = len(new_orders)

    log(f"✓ New orders found: {new_orders_count:,}")

    if new_orders_count == 0:
        log("⚠ No new orders found.")
        return

    del loading_df_unique
    gc.collect()

    # ================= AP DATA =================
    log("\n" + "=" * 70)
    log("STEP 4: Reading AP Data file...")
    log("=" * 70)

    ap_data_df = read_excel_optimized(
        ap_data_file,
        sheet_name="Data",
        usecols=["Sales No", "End Customer Name", "Business Model"]
    )

    ap_data_df["Sales No Clean"] = clean_and_normalize(ap_data_df, "Sales No")

    log(f"✓ Loaded {len(ap_data_df):,} AP records")

    # ================= MATCHING =================
    log("\n" + "=" * 70)
    log("STEP 5: Matching AP Data with new orders...")
    log("=" * 70)

    new_orders_set = set(new_orders["Sales No Clean"])

    mask = ap_data_df["Sales No Clean"].isin(new_orders_set)

    matched_ap_data = ap_data_df[mask][
        ["Sales No", "End Customer Name", "Business Model", "Sales No Clean"]
    ].copy()

    matched_count = len(matched_ap_data)
    unique_matched_sales = matched_ap_data["Sales No Clean"].nunique()
    match_rate = (unique_matched_sales / new_orders_count) * 100

    log(f"✓ Total matched rows: {matched_count:,}")
    log(f"✓ Unique Sales Nos matched: {unique_matched_sales:,}")
    log(f"✓ Match rate: {match_rate:.1f}%")

    if matched_count == 0:
        log("⚠ No AP matches found.")
        return

    del ap_data_df, new_orders
    gc.collect()

    # ================= FINAL CLEAN =================
    log("\n" + "=" * 70)
    log("STEP 6: Finalizing results...")
    log("=" * 70)

    final_result = matched_ap_data.drop_duplicates(
        subset=["Sales No", "End Customer Name", "Business Model"]
    ).reset_index(drop=True)

    final_count = len(final_result)

    log(f"✓ Final unique records: {final_count:,}")

    del matched_ap_data
    gc.collect()

    # ================= EXCEL OUTPUT =================
    log("\n" + "=" * 70)
    log("STEP 7: Creating Excel output...")
    log("=" * 70)

    wb = Workbook()
    ws = wb.active
    ws.title = "Final Output"

    headers = ["Sales No", "End Customer Name", "Business Model"]

    header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
    header_font = Font(bold=True, color="FFFFFF")

    for col, header in enumerate(headers, 1):
        cell = ws.cell(row=1, column=col, value=header)
        cell.font = header_font
        cell.fill = header_fill
        cell.alignment = Alignment(horizontal="center")

    for r_idx, row in enumerate(final_result[headers].itertuples(index=False), start=2):
        for c_idx, value in enumerate(row, start=1):
            ws.cell(row=r_idx, column=c_idx, value=value)

    ws.auto_filter.ref = ws.dimensions
    ws.freeze_panes = "A2"

    wb.save(output_file)

    # ================= SUMMARY =================
    log("\n" + "=" * 70)
    log("✓✓✓ PROCESS COMPLETED SUCCESSFULLY ✓✓✓")
    log("=" * 70)

    log("\n📊 SUMMARY:")
    log(f"  • Loading unique records: {loading_count:,}")
    log(f"  • Base unique records: {base_count:,}")
    log(f"  • New orders: {new_orders_count:,}")
    log(f"  • AP matched rows: {matched_count:,}")
    log(f"  • Final unique records: {final_count:,}")
    log("=" * 70)


def main():

    LOADING_FILE = r"C:\Users\W2625\Desktop\India Order Loading Week 01 Q3 FY2627.xlsx"
    BASE_FILE = r"D:\REL\OEM DATA\Q3'2627\OEM order list -- Q2'2627.xlsb"
    AP_DATA_FILE = r"C:\Users\W2625\Downloads\AP Data Q3'2627 Oct-07.xlsb"

    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

    OUTPUT_FOLDER = r"C:\Users\W2625\Desktop\OEM output"

    if not os.path.exists(OUTPUT_FOLDER):
        os.makedirs(OUTPUT_FOLDER)

    OUTPUT_FILE = os.path.join(
        OUTPUT_FOLDER,
        f"Final_Output_{timestamp}.xlsx"
    )

    start_time = datetime.now()

    process_oem_orders_advanced(
        LOADING_FILE,
        BASE_FILE,
        AP_DATA_FILE,
        OUTPUT_FILE
    )

    duration = (datetime.now() - start_time).total_seconds()
    print(f"\n⏱ Total execution time: {duration:.2f} seconds")


if __name__ == "__main__":
    main()

Appendix B – Overall vs Base Python Code

The following is the code supplied for Process 2. Update FYQ_VALUE and file paths for the reporting period before execution.

import pandas as pd
import os
from datetime import datetime

# ================== CONFIGURATION ==================
FYQ_VALUE = "FY2627Q3"   # <<< UPDATE THIS if quarter changes
REGION_VALUE = "INDIA"
# ===================================================


def process_overall_vs_base(base_file, overall_file, output_file):

    print("Reading Base File...")
    base_df = pd.read_excel(base_file, dtype=str)

    print("Reading Overall File...")
    overall_df = pd.read_excel(overall_file, dtype=str)

    # Clean column names (avoid hidden spaces issue)
    base_df.columns = base_df.columns.str.strip()
    overall_df.columns = overall_df.columns.str.strip()

    # Clean key columns
    base_df["Sales No"] = base_df["Sales No"].astype(str).str.strip()
    overall_df["SO_No"] = overall_df["SO_No"].astype(str).str.strip()

    print("Performing VLOOKUP logic...")

    # VLOOKUP equivalent (Left merge)
    merged_df = overall_df.merge(
        base_df[["Sales No"]],
        left_on="SO_No",
        right_on="Sales No",
        how="left",
        indicator=True
    )

    # Keep only matched records (remove #N/A equivalent)
    matched_df = merged_df[merged_df["_merge"] == "both"].copy()

    print(f"Matched Records: {len(matched_df)}")

    # Create final output format
    final_df = pd.DataFrame({
        "Region": REGION_VALUE,
        "SalesOrder": matched_df["SO_No"],
        "MTM": matched_df["Material"],
        "Customer Name": matched_df["Name of End Customer"],
        "FYQ": FYQ_VALUE
    })

    # Save to Excel
    with pd.ExcelWriter(output_file, engine="openpyxl") as writer:
        final_df.to_excel(writer, sheet_name="Final Output", index=False)

    print("Process Completed Successfully!")
    print("Output saved to:", output_file)


def main():

    BASE_FILE = r"D:\REL\OEM DATA\Q3'2627\OEM order list -- Q3'2627.xlsb"
    OVERALL_FILE = r"C:\Users\W2625\Downloads\Overall 1-1791352210773.xlsb"
    OUTPUT_FOLDER = r"C:/Users/W2625/Desktop/OEM output"

    if not os.path.exists(OUTPUT_FOLDER):
        os.makedirs(OUTPUT_FOLDER)

    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

    OUTPUT_FILE = os.path.join(
        OUTPUT_FOLDER,
        f"Overall_Base_Matched_{timestamp}.xlsx"
    )

    process_overall_vs_base(BASE_FILE, OVERALL_FILE, OUTPUT_FILE)


if __name__ == "__main__":
    main()

Appendix C – Python Code Explanation

This appendix explains the two scripts included in Appendix A and Appendix B. It describes the purpose of the main code blocks and important functions in plain language. The explanations are based on the code included in this SOP.

C.1 Script 1 – OEM Order Loading and AP Data Matching

Objective: identify Sales Numbers in the current OEM Order Loading file that are not already present in the OEM Base, then look up those Sales Numbers in AP Data to retrieve End Customer Name and Business Model. The script writes the matched, de-duplicated records to a new Excel file.

1. Importing libraries

The import statements load the tools the script uses.

  • pandas (pd): reads and processes tabular data. Used for Excel/CSV input and data filtering.
  • numpy (np): imported in this script, but the code shown does not directly use it.
  • openpyxl Workbook and formatting classes: create the output workbook, add the header row, apply formatting, filters, and freeze panes.
  • os: checks file extensions and folders, and builds output paths.
  • datetime: creates timestamps for logging and the output filename.
  • gc: requests garbage collection after large DataFrames are no longer needed, helping release memory.

2. Configuration switches

USE_CHUNKING and CHUNK_SIZE are configuration variables for chunk processing, but the supplied code does not use them in the current workflow. ENABLE_LOGGING controls whether messages from the log() function are printed.

3. log(message)

This helper function prints progress messages with the current time when ENABLE_LOGGING is True. It helps the user see which step is running and how many records were loaded, matched, or saved.

4. read_excel_optimized(file_path, sheet_name, usecols)

This helper selects a reader based on the file extension and reads the requested columns as text (dtype=str).

  • .xlsb files are read using the pyxlsb engine; .xls files use xlrd; .csv files use read_csv; other file types use openpyxl.
  • usecols limits the input to the required columns, reducing unnecessary data loading.
  • For the AP Data input, the script specifies sheet_name="Data". The sheet name must therefore match exactly unless the code is updated.

5. clean_and_normalize(df, column)

This function creates a normalized text version of a column for matching. It converts values to strings, removes leading/trailing spaces, changes text to uppercase, and replaces repeated whitespace with a single space. This helps prevent mismatches caused by capitalization or spacing.

6. Read and prepare OEM Order Loading

The script reads only Sales No and End Customer Name from the current loading file. It creates helper columns named Sales No Clean and Customer Clean using clean_and_normalize(). It then removes duplicate rows using both normalized keys and resets the row index. The original displayed values are retained for the final output.

7. Read the OEM Base

The script reads Sales No and End Customer Name from the base file, normalizes the Sales No column, and creates a set of unique normalized Sales Numbers. A set makes membership checks efficient. Although End Customer Name is loaded from the base, the current new-order test uses Sales No only.

8. Identify new Sales Numbers

The expression ~loading_df_unique["Sales No Clean"].isin(base_sales_orders) marks loading records whose normalized Sales No is not present in the base. Those records are retained in new_orders. If no new Sales Numbers are found, the script logs a message and returns without creating an output file.

9. Read AP Data

The script reads the Data sheet from AP Data, using Sales No, End Customer Name, and Business Model. It normalizes AP Data Sales No values so they can be compared with the new-order Sales Numbers.

10. Match new orders with AP Data

The script creates a set of new normalized Sales Numbers and filters AP Data to rows whose normalized Sales No appears in that set. It reports the number of matching rows, unique matched Sales Numbers, and a match rate. If no AP rows match, it logs a message and returns without creating an output file.

11. Remove duplicate final records

The matched records are de-duplicated using the original Sales No, End Customer Name, and Business Model columns. The final output therefore keeps unique combinations of those three fields.

12. Create and format the Excel output

The script creates a workbook with a worksheet named Final Output and writes three columns: Sales No, End Customer Name, and Business Model. It formats the header with a blue fill, bold white text, and centered alignment; adds an autofilter; freezes the first row; and saves the workbook to the configured output path.

13. main() and execution

main() contains the input paths, creates the output folder if needed, adds a timestamp to the output filename, records the start time, and calls process_oem_orders_advanced(). It then prints the total execution time. The final if __name__ == "__main__" check runs main() when the script is executed directly.

C.2 Script 2 – Overall Report and OEM Base Matching

Objective: retain rows in the Overall Report whose SO_No exists in the OEM Base Sales No column, then create a standardized output with Region, SalesOrder, MTM, Customer Name, and FYQ.

1. Importing libraries and configuration

pandas handles the tabular data, os handles folder and file paths, and datetime creates a timestamp. FYQ_VALUE is set to FY2627Q3 and REGION_VALUE is set to INDIA. Update FYQ_VALUE when the reporting quarter changes.

2. Read the two workbooks

The script reads the OEM Base and Overall Report with pd.read_excel(..., dtype=str), treating values as text. Because sheet_name is not specified, pandas reads the first worksheet in each workbook.

3. Clean column names and matching keys

The script strips leading and trailing spaces from column names, then converts Sales No and SO_No to strings and strips spaces from their values. This reduces matching issues caused by whitespace. Unlike Script 1, this script does not convert the matching keys to uppercase or collapse repeated internal spaces.

4. Perform the VLOOKUP-equivalent merge

overall_df.merge(...) joins Overall Report rows to the Sales No column from the base, matching SO_No to Sales No. how="left" keeps all rows from the Overall Report during the join. indicator=True adds a helper column called _merge to identify whether each row matched.

5. Keep only matched rows

The filter _merge == "both" keeps records that were found in both files. This is the equivalent of keeping successful lookup results and removing rows that would return #N/A. The script prints the number of matched records.

6. Build the final output columns

The script creates a new DataFrame with Region set to INDIA, SalesOrder taken from SO_No, MTM taken from Material, Customer Name taken from Name of End Customer, and FYQ set to the configured quarter value. These source columns must exist in the Overall Report.

7. Save the output

pd.ExcelWriter saves the result to a new Excel file in a worksheet named Final Output, without adding a separate index column. The filename includes a timestamp so that separate runs generally create separate output files.

8. main() and execution

main() defines the base and Overall Report paths, creates the output folder if it does not exist, builds the timestamped output filename, and calls process_overall_vs_base(). The final if __name__ == "__main__" check starts the process when the script is run directly.

C.3 Key Python Functions Used

Function / Method Purpose
pd.read_excel() Reads an Excel worksheet into a pandas DataFrame.
pd.read_csv() Reads a CSV file into a pandas DataFrame.
astype(str) Converts values to strings so IDs can be handled consistently as text.
str.strip() Removes spaces at the beginning and end of text.
str.upper() Converts text to uppercase for case-insensitive comparison.
str.replace(r"\s+", " ", regex=True) Replaces repeated whitespace inside text with a single space.
drop_duplicates() Removes duplicate rows based on all columns or the specified subset of columns.
isin() Checks whether each value exists in a list, set, or Series.
set() Creates a collection of unique values and supports efficient membership checks.
merge() Joins two DataFrames using matching key columns, similar to a database join or Excel lookup.
pd.ExcelWriter() Writes a DataFrame to an Excel workbook and worksheet.
os.path.exists() / os.makedirs() Checks whether a folder exists and creates it if necessary.
os.path.join() Combines folder and filename parts into a file path.
datetime.now().strftime() Formats the current date/time, used here to create timestamped filenames.
enumerate() Loops through items while also providing a counter, used to place values in Excel cells.

C.4 Operational Checks and Known Limitations

  • Confirm all input file paths exist and the input files are the intended reporting-period versions.
  • Confirm required worksheet names and column headers match the code exactly. Script 1 expects an AP Data worksheet named Data and does not currently handle DATA automatically.
  • Script 1 identifies new orders by Sales No only. Customer name is used to deduplicate loading rows, but is not part of the comparison against the OEM Base.
  • Script 1 exits early when no new orders or no AP matches are found; in either case, the expected output workbook may not be created.
  • Script 2 matches SO_No to Sales No after trimming outer spaces, but does not normalize case or repeated internal spaces.
  • Script 2 reads the first worksheet in each workbook because no sheet_name is specified.
  • Script 2 requires Material and Name of End Customer columns in the Overall Report and Sales No in the OEM Base.
  • Before using the output for reporting, verify the record counts, spot-check several Sales Numbers, confirm the quarter value, and ensure the output reflects the intended source files.

Important: The explanations above describe the current code. If the scripts are changed later, update this appendix so the SOP remains aligned with the automation.