繁体   English   中英

有没有办法将特定列从 Excel 工作表(例如 sheet_1)复制到 sheet_2 中的另一列? 使用 Python

[英]Is there any way to copy a particular column from excel sheet (say sheet_1) to the other column which is in sheet_2? Using Python

请在下面找到代码:

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()

在这段代码中,它正在替换目标 excel 文件的现有内容。 我想在不更改其他列的情况下更新工作表 2 中的列。

例子:

Excel 文件 1--> column_name = 'Marks'

标记 = 10,20,30

Excel 文件 2--> 此文件中有两列

Subject_name = 数学、英语、科学

分数 = 50, 20, 40

所以我想从 Excel 文件 1 复制“标记”列并将其粘贴到 Excel 文件 2 的“标记”列中(不更改“主题”列的数据)

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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM