Python Script to transfer select data from spreadsheet "A to spreadsheet "B"

30 views Asked by At

Located a python script (Included below) that will allow me to do this with user intervention but I need the Python script to read and write the data automatically. Preferable with "pandas" and "openpyxly" 1: Read from spreadsheet "SOdata.xlsx" all cells with data in column (A) "QTY" and (B) "ITEM". 2: Write column (A) "QTY" data to spreadsheet "ToBePrinted.xlsx" if data in column (B) "ITEM" cells match.

Source SpreadsheetDestination Spreadsheet

import openpyxl
import pandas as pd
import shutil

import warnings
warnings.filterwarnings('ignore') # setting ignore as a parameter

###Daily Data df2

daily_data = ('ToBePrinted.xlsx')

Master Data df1

master_data = 'SOdata.xlsx'
worksheet = "Sheet1"

Example sheet IDs A, B, C, D, E, F, G, H,

Get IDs from the user (comma separated entry) and add to list ids_list

input_ids = input("Enter the IDs to obtain: ")

Load the Master sheet to Pandas for searching

df1 = pd.read_excel(master_data, sheet_name=worksheet)

Load the Daily sheet to Pandas for searching

df2 = pd.read_excel(daily_data, sheet_name=worksheet)

Column names for writing back to excel sheet

column_list = df2.columns

Open writer for pandas dataframe (df) write back to excel

mode a = append, overlay the existing sheet

writer = pd.ExcelWriter(daily_data,
                mode='a', 
                if_sheet_exists='overlay',
                engine='openpyxl')

for uid in ids_list:

### Search 1st col of XLSX2 df for the ID

search1 = df1.loc[df1.iloc[:,0] == uid]

### If search returns a value then add to the location

if search1.size > 0:
    
    ### Search 1st col of XLSX1 dataframe for the ID
    
    search2 = df2.loc[df2.iloc[:,0] == uid]
    
    ### Update XLSX1 df with the data value from XLSX2 df
    
    df2.at[search2.index[0], df2.iloc[:, 1].name] = df1.iloc[:,1].loc[search1.index[0].item()]

Write updated dataframe to XLSX1 sheet

df2.to_excel(writer, sheet_name=worksheet, startrow=1, header=False, index=False)

Drop pandas header formatting

book  = writer.book
sheet = writer.sheets[worksheet]
for idx, val in enumerate(column_list,1):
sheet.cell(row=1, column=idx).value = val

Save XLSX1 workbook

writer.close()

#Copy A to C

shutil.copyfile('ToBePrinted.xlsx', 'CXLSX3.xlsx')
0

There are 0 answers