我正在尝试将每个空单元格切换为填充数字 1 的单元格

I am trying to switch every empty cell to one filled with the number 1

您好,我目前正在使用 openpyxl,我正在尝试将每个空单元格换成数字为 1 的单元格,然后最后用红色填充一个单元格。到目前为止,这是我的代码:

import openpyxl
from openpyxl.styles import Color, PatternFill, Font, Border
from openpyxl.utils import column_index_from_string

#redFill = PatternFill(fill_type=None, start_color='F2DCDB', end_color='F2DCDB')




wb = openpyxl.load_workbook('MRR.xlsx')
sheet = wb["Monthly MRR "]

for r in range(7, 793):
    for col in range(4,21):
        current_cell = sheet.cell(row=r, column=col).value
        if current_cell == None:
            current_cell = "LL"


wb.save("updatedMRR.xlsx")

尽管我遍历了每个项目,它似乎并没有改变任何单元格。

您应该更改您的代码,以便您引用实际的单元格并明确检查和设置它的值。您的代码当前检查值的副本,然后覆盖副本而不是实际单元格。

current_cell = sheet.cell(row=r, column=col) if current_cell.value is None: current_cell.value = "LL" PS 使用 ws.iter_rows() 而不是您自己的计数器。