Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

python - Copy paste column range using OpenPyxl

Hi so I am trying to copy and paste W7:W46 column into another worksheet. The code I have so far,

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

is able to copy over the entire column, but unfortunately transfers the various headers as well. One solution I have tried is:

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

But that only copies the first value of W7

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Copy a Range(['W7:W46']) from one Worksheet to another Worksheet:
If the Ranges are not overlapping, it's also possible in the same Worksheet.

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

If you want to do the above with multiple different Columns, use the above in a 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)

Tested with Python: 3.4.2 - openpyxl: 2.4.1 - LibreOffice: 4.3.3.2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...