我是Python的新手,我正在尝试使用openpyxl库使我的一些VBA代码适应Python。在这种情况下,我尝试根据标题中的字符串从工作簿中复制单列中的468行,并将它们粘贴到另一个特定列中的另一个工作簿中,该列具有另一个特定字符串作为标题。我不能简单地选择我想要复制的单元格的范围,因为这是报表自动化的一部分,标题会随着文件的不同而改变位置。
我需要使用什么函数将一个工作簿中的468个单元格复制到第二个工作簿的468个单元格中?或者,如何复制单元格区域,然后将其粘贴到另一个工作簿中?下面是我的代码,我知道问题出在哪里:我将一个单元格(第一个工作簿中的最后一个单元格)重复复制到第二个工作簿的468个单元格中。
#!/usr/bin/python3
import pdb
import openpyxl
from openpyxl.utils import column_index_from_string
wb1 = openpyxl.load_workbook('.../Extraction.xlsx')
wb2 = openpyxl.load_workbook('.../Template.xlsx')
ws1 = wb1.active
first_row1 = list(ws1.rows)[0] #to select the first row (header)
for cell in first_row1:
if cell.value == "email":
x = cell.column #to get the column
y = column_index_from_string(x) #to get the column's index
for i in range(2, 469):
cell_range1 = ws1.cell(i, y) #the wrong part
ws2 = wb2.active
first_row2 = list(ws2.rows)[0]
for cell in first_row2:
if cell.value == "emailAddress":
w = cell.column
z = column_index_from_string(w)
for o in range(2, 469):
cell_range2 = ws2.cell(o, z)
cell_range2.value = cell_range1.value
path = '.../Test.xlsx'
wb2.save(path)
发布于 2018-03-28 01:17:10
您可能需要将输入翻转到.cell()
,我猜它是.cell(column, row)
。或者只使用关键字.cell(column=z, row=o)
您需要为这两个行迭代器创建动态索引,同时将列索引保留在找到它们的位置:
for o in range(2, 469):
#note the common o for both, could also be o+1 for one if there is an offset
ws2.cell(o, z).value = ws1.cell(o, y).value
发布于 2019-12-11 18:43:15
实际上,创建这样一个函数非常容易:
from openpyxl.utils import rows_from_range
def copy_range(range_str, src, dst):
for row in rows_from_range(range_str):
for cell in row:
dst[cell].value = src[cell].value
return
请注意,range_str是一个常规字符串,比如"A1:B2“,src和dest都必须是有效的sheet对象。但是,如果您正在复制大范围,这可能需要一段时间,因为读/写似乎相当耗时。
https://stackoverflow.com/questions/49518071
复制相似问题