首页 > 解决方案 > 将值附加到特定列 openpyxl

问题描述

试图从 ws2 中获取一组数据并附加到 ws3 的底部。我正在努力附加到 ws3 上的特定列。

目前,所有内容都只是附加到 A 列,尽管我希望它附加到 ws2 中信息来自的相同列。

#where I want to copy data from:
for col in ws2.iter_cols(min_row=2,min_col=4,max_col=6):
    for cell in col:
        ws3.append([cell.value])

wb3.save('example3.xlsx')

帮助!

标签: pythonopenpyxl

解决方案


现在,在 2020 年,有一种更方便的方法可以解决这个问题:

文档

append(iterable)

Appends a group of values at the bottom of the current sheet.

    If it’s a list: all values are added in order, starting from the first column
    If it’s a dict: values are assigned to the columns indicated by the keys (numbers or letters)

Parameters: iterable (list|tuple|range|generator or dict) – list, range or generator, or dict containing values to append

Usage:

    append([‘This is A1’, ‘This is B1’, ‘This is C1’])
    or append({‘A’ : ‘This is A1’, ‘C’ : ‘This is C1’})
    or append({1 : ‘This is A1’, 3 : ‘This is C1’})

Raise:  TypeError when iterable is neither a list/tuple nor a dict

所以,在你的代码中,它应该是这样的:

ws3.append({col: cell.value})

推荐阅读