我是Python的新手,我正在尝试使用OpenPyXl库将一些VBA代码调整为它。在这种特殊情况下,我正在尝试根据标题中的字符串从工作簿中的单个列中复制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)
创建这样的函数实际上很容易:
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都必须是有效的表对象。但是,如果您要复制大型范围,这可能需要一段时间,因为阅读/写入似乎很耗时。
您可能必须将输入翻转为 .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