使用OpenPyxl复制粘贴列范围

时间:2017-07-05 13:49:54

标签: python openpyxl

您好我正在尝试将W7:W46列复制并粘贴到另一个工作表中。我到目前为止的代码,

col_j = New_Burden['W']
for idx, cell in enumerate(col_j,1):
    ws1.cell(row = idx, column = 10).value = cell.value

能够复制整个列,但遗憾的是也会传输各种标题。我尝试过的一个解决方案是:

for row in New_Burden['W7:W46']:
    for cell in row:
        ws1.cell(row = 2, column = 10).value = cell.value

但那只复制了W7的第一个值

1 个答案:

答案 0 :(得分:1)

将范围(['W7:W46'])从一个工作表复制到另一个工作表:
如果范围重叠,也可以在同一工作表中使用。

from openpyxl import Workbook
# Create a new Workbook
wb = Workbook()
ws = wb.worksheets[0]

from openpyxl.utils import range_boundaries
# Define start Range(['J2']) in the new Worksheet
min_col, min_row, max_col, max_row = range_boundaries('J2')

# Iterate Range you want to copy
for row, row_cells in enumerate(New_Burden['W7:W46'], min_row):
    for column, cell in enumerate(row_cells, min_col):
        # Copy Value from Copy.Cell to given Worksheet.Cell
        ws.cell(row=row, column=column).value = cell.value

如果您想使用多个不同的列进行上述操作, 在function

中使用上述内容
def copy_range(source_range, target_start):
    # Define start Range(target_start) in the new Worksheet
    min_col, min_row, max_col, max_row = range_boundaries(target_start)

    # Iterate Range you want to copy
    for row, row_cells in enumerate(New_Burden[source_range], min_row):
        for column, cell in enumerate(row_cells, min_col):
            # Copy Value from Copy.Cell to given Worksheet.Cell
            ws.cell(row=row, column=column).value = cell.value

for source_range, target_start in [('W7:W46','J2'), ('Y7:Y46','A2')]:
    copy_range(source_range, target_start)

使用Python测试:3.4.2 - openpyxl:2.4.1 - LibreOffice:4.3.3.2