Python Forum

Full Version: Copy column from one existing excel file to another file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm new on forum, and I'm python beginner. I'm tried to search solution, but I didn't find the same post like this, just little similar, but I can't take advantage of. I have a problem with code, its working well but not in 100% like I want, I have no idea where's problem, because code copy column from one Excel file to another, but paste it with creating another one sheet, with the same name, not open and paste in already created sheet. Code should make :

Open excel file named "ExcelFile1" Go to Sheet "ION" -> Copy column named "A" and column named "G" -> Open second Excel file "Costs" Go to Sheet "Cost" -> paste column "A" to column named "B" and paste column "G" to column named "C"

In next step code delete duplication's but it work well.

Here's the code :

import pandas as pd
 
first_file_name = "ION.xlsx" 
second_file_name = "Costs.xlsx"
 
#Load data from file.

xl = pd.ExcelFile(first_file_name)
df = xl.parse("AIONS")
column = df['A'] # column to copy.
 
new_xl = pd.ExcelFile(second_file_name)
print(new_xl.sheet_names)
new_df['A'] = column #name of column in new excel file.
 
#Paste it in the new excel file.
with pd.ExcelWriter(second_file_name, mode='a') as writer:
    new_df.to_excel(writer, sheet_name="Cost", index=False)
^ in my screen is named Cost and there should be pasted :

[Image: JECIg.png]

But like we can see there's created another one sheet Cost1

To delete duplicate I use :

#Delete duplicate  

import pandas as pd

file_df = pd.read_excel("ExcelFile")

#Keep only FIRST record from set of duplicates
file_df_first_record = file_df.drop_duplicates(subset=["A", "B"], keep="first")
file_df_first_record.to_excel("WO Duplicates.xlsx", index=False) 
Can someone suggest me how to build it or just fix it :)

All the best!