0

私はPythonが初めてで、openpyxlライブラリを使用してVBAコードの一部をPythonに適応させようとしています. この特定のケースでは、ヘッダーの文字列に従ってブックから 1 つの列に 468 行をコピーし、ヘッダーとして別の特定の文字列を持つ特定の列の別のブックに貼り付けようとしています。これはレポートの自動化の一部であり、ヘッダーの位置はファイルごとに変わるため、コピーしたいセルの範囲を単純に選択することはできません。

468 セルのそれぞれを 1 つのワークブックから 2 番目のワークブックの 468 セルにコピーするために使用する必要がある関数は何ですか? または、セルの範囲をコピーして別のブックに貼り付けるにはどうすればよいですか? これが私のコードで、何が問題なのかを正確に知っています。1 つのセル (最初のブックの最後のセル) を 2 番目のブックの 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)
4

2 に答える 2