简体   繁体   English

根据特定的单元格值复制一行openpyxl

[英]Copy a row based on a specific cell value openpyxl

I trying to get openpyxl to copy and paste rows to a new excel spreadsheet.我试图让 openpyxl 将行复制并粘贴到新的 excel 电子表格中。 The only rows that need to get copy and pasted contain the value "move" in the B column.唯一需要复制和粘贴的行在 B 列中包含值“move”。

There are many ways to do it so the example it not specific to what you are doing.有很多方法可以做到这一点,所以这个例子并不特定于你在做什么。 To get your data in to the dataframe documentation .将您的数据写入 dataframe 文档

import pandas as pd
from openpyxl import load_workbook

path = "C:/path to/your file/example.xlsx"
df = pd.read_excel(path, sheet_name='Sheet1', usecols='A,B,C')

# for demo purposes the column head names are ['A','B','C']
df = df[df['B']=='move']

wb = load_workbook(path, data_only=True)
sh = wb["move"]
# lets have the rows start on line 4 because for what ever reason...
rows = df.shape[0] + 4
for r in range(4, rows):
    # df values for the table
    i = r - 4
    sh.cell(column=1, row=r).value = df["A"].iloc[i]
    sh.cell(column=2, row=r).value = df["B"].iloc[i]
    sh.cell(column=3, row=r).value = df["C"].iloc[i]

wb.save(path)

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

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