在Python 3中使用OpenPyXL复制整个列

时间:2018-02-05 10:32:30

标签: python openpyxl

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

我有一个工作簿,其中包含一个工作表,其中包含A列和JX列中的日期加载(A包含每月日期,JX包含季度日期)。我希望将每月日期列(在A:A中)复制到以' M'结尾的每个工作表。在我的目标工作簿中,季度日期列(在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。它不应该跨行循环..?

1 个答案:

答案 0 :(得分:0)

在电子表格编辑器中加载新的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') 
相关问题