如何将相同的值追加到列中直到达到最大行?

How to append the same value down a column until it reaches the max row?

我正在尝试将一个新值传递给从 B2 开始并循环到最大行的 B 列。

import openpyxl
import os

# Finds current directoryhow
current_path = os.getcwd()
print(current_path)

# Changes directory
os.chdir('C:\Users\satwood\Documents\Example')

# prints new current directory
new_path = os.getcwd()
print(new_path)

# load workbooks
wb = openpyxl.load_workbook('example.xlsx')
type(wb)

# load worksheets
ws1 = wb.active

# append column B with cell_example

cell_example = ['success one']

max = ws1.max_row

for row, entry in enumerate(cell_example, start=1):
    ws1.cell(row=row + max, column=1, value=entry)

wb.save('example.xlsx')

这段代码的输出是: None None None None None None ...

您的代码没有按照您的预期执行。您正在遍历 cell_example,这是一个只有 1 个项目 ('success one') 的列表。您的循环运行一次,行等于 1+max_row 并且条目是 success one 分配给单元格 A{1+max_row}.

请注意,B 列是 B 使用 ws['B{row}']2 使用您在代码中的使用方式。

如果您尝试向 B 列中 max_row 之前的所有单元格添加相同的值,那么您只需将循环更改为:

for row in range(2, max_row):
    ws1.cell(row=row, column=2, value=cell_example[0])

但是,如果您希望遍历 cell_example 中的列表并将它们分配给 B 列,那么您可以使用:

for row, entry in enumerate(cell_example, start=2):
    ws1.cell(row=row, column=2, value=entry)

这会将列表 cell_example 中的项目添加到从单元格 B2 开始的 B 列中。

请注意 stovfl 所说的并指出迭代列中单元格的更好方法是使用:

for col_cells in worksheet.iter_cols(min_col=2, max_col=2):
    for cell in col_cells:
        cell.value = "Something"

正如他提到的 中所述。