在 Python 3 中使用 OpenPyXL 复制整列

Copying an entire column using OpenPyXL in Python 3

我正在尝试使用 OpenPyXL 复制整个专栏。 Google 似乎提供了很多使用范围的示例,但不是针对整个列。

我有一个工作簿,其中有一个工作表,A 列和 JX 列中有大量日期(A 包含每月日期,JX 包含季度日期)。我希望将每月日期列(在 A:A 中)复制到目标工作簿中以 'M' 结尾的每个工作表,并将季度日期列(在 JX:JX 中)复制到以 JX:JX 结尾的工作表在 'Q'.

但是,由于某些原因,最后一个嵌套的 for 循环 for src, dst in zip(ws_base[monthRange], ws_target['A:A']): 只复制了第一个单元格,没有其他内容。看起来我正在用我的 monthRangequarterRange 字符串识别正确的列,但是 Python 并没有遍历整个列,尽管我已经定义了两个范围.

有没有人有什么想法?

# Load the target workbook
targetwb = openpyxl.load_workbook('pythonOutput.xlsx')


# Load the source workbook
wb_base = openpyxl.load_workbook('Baseline_IFRS9_' + reportingMonth+'.xlsx')

# Go to row 9 and find "Geography:" to identify the relevant 
# month and quarter date columns

sentinel = u"Geography:"
ws_base = wb_base.active

found = 0
dateColumns = []

for column in ws_base:
    for cell in column:
        if cell.value == sentinel:
            dateColumns.append(cell.column) #
            found + 1

            if found == 2:
                break


ColumnM = dateColumns[0]
ColumnQ = dateColumns[1]

print('Monthly col is ' + ColumnM)
print('Quarterly col is ' + ColumnQ)

IndexM = int(openpyxl.utils.column_index_from_string(str(ColumnM)))
IndexQ = int(openpyxl.utils.column_index_from_string(str(ColumnQ)))

print('Monthly col index is ' + str(IndexM))
print('Quarterly col index is ' + str(IndexQ))

print('Proceeding to paste into our new workbook...')

sheetLoop = targetwb.get_sheet_names()


for sheets in sheetLoop:
    if sheets.endswith('Q'):
        ws_target = targetwb[sheets]
        quarterRange = ColumnQ + ':' + ColumnQ

        print('Copying and pasting quarterly dates into: ' + sheets)
        for src, dst in zip(ws_base[quarterRange], ws_target['A:A']):
            dst.value = src.value

    elif sheets.endswith('M'):
        ws_target = targetwb[sheets]
        monthRange = ColumnM + ':' + ColumnM

        print('Copying and pasting monthly dates into: ' + sheets)
        for src, dst in zip(ws_base[monthRange], ws_target['A:A']):
            dst.value = src.value

targetwb.save('pythonOutput.xlsx')

这是我的问题的更简单形式。

import openpyxl

wb1 = openpyxl.load_workbook('pythonInput.xlsx')
ws1 = wb1.active

wb2 = openpyxl.load_workbook('pythonOutput.xlsx')
ws2 = wb2.active

for src, dst in zip(ws1['A:A'], ws2['B:B']):
    print( 'Printing from ' + str(src.column) + str(src.row) + ' to ' + str(dst.column) + str(dst.row))
    dst.value = src.value

wb2.save('test.xlsx') 

所以这里的问题是for循环只打印从A1到B1。它不应该跨行循环..?

当您在电子表格编辑器中加载新的 XLSX 时,您会看到网格中有很多很多空单元格。然而,这些空单元格实际上是从文件中省略的,只有当它们具有非空值时才会被写入。你可以自己看看:XLSX 本质上是一堆 ZIP 压缩的 XML,可以用任何存档管理器打开。

以类似的方式,OpenPyXL 中的新单元仅在您访问它们时创建。 ws2['B:B']范围只包含一个单元格B1,并且zip在最短迭代器用完时停止。

考虑到这一点,您可以遍历源范围并使用显式坐标将值保存在正确的单元格中:

import openpyxl

wb1 = openpyxl.load_workbook('pythonInput.xlsx')
ws1 = wb1.active

wb2 = openpyxl.load_workbook('pythonOutput.xlsx')
ws2 = wb2.active

for cell in ws1['A:A']:
    print('Printing from ' + str(cell.column) + str(cell.row))
    ws2.cell(row=cell.row, column=2, value=cell.value)

wb2.save('test.xlsx')