将值附加到特定列openpyxl

时间:2019-02-12 00:57:32

标签: python 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')

帮助!

2 个答案:

答案 0 :(得分:0)

您只能追加行,但可以轻松调整代码以使其与此配合使用:

for col in ws2.iter_rows(min_row=2,min_col=4,max_col=6):
    row = [None]*3 + [cell.value for cell in col]
    ws3.append(row)

答案 1 :(得分:0)

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

来自docs

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})