Please find the code below:
import pandas as pd
import csv
# Reading the csv file
df_new = pd.read_csv('source.csv')
# saving xlsx file
GFG = pd.ExcelWriter('source.xlsx')
df_new.to_excel(GFG, index = False)
GFG.save()
# read excel
xl = pd.ExcelFile("source.xlsx")
df = xl.parse("Sheet1")
# get the column you want to copy
column = df["Marks"]
# paste it in the new excel file
with pd.ExcelWriter('Target_excel.xlsx', mode='A') as writer:
column.to_excel(writer, sheet_name= "new sheet name", index = False)
writer.close()
In this code, it is replacing the existing contents of the target excel file. I want to update a column in sheet 2 without changing other columns.
Example:
Excel file 1--> column_name = 'Marks'
Marks = 10,20,30
Excel file 2--> there are two columns present in this file
Subject_name = Math, English, Science
Marks = 50, 20, 40
So I want to copy "Marks" column from Excel file 1 and paste it into "Marks" column of Excel file 2(Without changing the data of "Subject" column)
import pandas as pd
import openpyxl as pxl
def get_col_idx(worksheet, col_name):
return next((i for i, col in enumerate(worksheet.iter_cols(1, worksheet.max_column)) if col[0].value == col_name), -1)
### ----- 0. csv -> xlsx (no change from your code)
df_new = pd.read_csv("source.csv")
GFG = pd.ExcelWriter("source.xlsx")
df_new.to_excel(GFG, index=False)
GFG.save()
### ----- 1. getting data to copy
# open file and get sheet of interest
source_workbook = pxl.load_workbook("source.xlsx")
source_sheet = source_workbook["Sheet1"]
# get "Marks" column index
col_idx = get_col_idx(source_sheet, "Marks")
# get contents in each cell
col_contents = [row[col_idx].value for row in source_sheet.iter_rows(min_row=2)]
### ----- 2. copy contents to target excel file
target_workbook = pxl.load_workbook("Target_excel.xlsx")
target_sheet = target_workbook["new sheet name"]
col_idx = get_col_idx(target_sheet, "Marks")
for i, value in enumerate(col_contents):
cell = target_sheet.cell(row=i+2, column=col_idx+1)
cell.value = value
target_workbook.save("Target_excel.xlsx")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.