简体   繁体   English

Python 程序不写入 Excel 单元

[英]Python program does not write to an Excel cell

First row is the header I then want cells to be printed.第一行是 header 然后我想要打印单元格。 The code runs successfully.代码运行成功。 Creates the file and the header but does not print the values like Cars, 10 etc from row 2. What's wrong in the code?创建文件和 header 但不打印第 2 行中的 Cars、10 等值。代码有什么问题? Thanks !谢谢 !

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

The reason that the rows are not being filled in is because of the for loop condition.未填充行的原因是因为 for 循环条件。 According to the documentation, cells are not created in memory until they are accessed.根据文档,在访问单元之前,不会在 memory 中创建单元。 So you only create one row meaning that the maximum will be one.因此,您只创建一行,这意味着最大值将为一。 By changing the value of row1 to a static number, you will see that it will put the values into the cell.通过将 row1 的值更改为 static 数字,您将看到它将值放入单元格中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM