我是 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)