Python 程序不写入 Excel 单元格

Python program does not write to an Excel cell

第一行是 header 然后我想要打印单元格。代码运行成功。创建文件和 header 但不打印第 2 行中的 Cars、10 等值。代码中有什么问题?谢谢!

from openpyxl import Workbook

wb = Workbook() #object of Workbook type
print(wb.active.title)
print(wb.sheetnames)
wb['Sheet'].title="Report_Amount"
sh1 = wb.active  
sh1['A1'].value = "Item"       #Writing into the cell to create header
sh1['B1'].value = "Quantity"
sh1['C1'].value = "Price($)"
sh1['D1'].value = "Amount($)"

column1 = sh1.max_column
row1 = sh1.max_row
print(f'no. of columns : {column1}')
print(f'no. of rows : {row1}')
for i in range (2, row1+1):  #want to write values from row #2
    for j in range (1, column1+1):
        sh1.cell(row=i,column=j).value = "Cars"
        sh1.cell(row=i, column = j+1).value = 5
        sh1.cell(row=i, column = j+2).value = 10000
        sh1.cell(row=i, column = j+3).value = 50000
     
print("file saved")
wb.save("C:\Users\Ricky\Desktop\FirstCreatedPythonExcel1.xlsx")

行没有被填充的原因是因为for循环条件。根据文档,单元格在被访问之前不会在内存中创建。所以你只创建一行,这意味着最大值是一。通过将 row1 的值更改为静态数字,您将看到它会将值放入单元格中。