Home > Blockchain >  Set value of multiple cells with Openpyxl
Set value of multiple cells with Openpyxl

Time:04-24

I'm got into programming because of the tasks I do at work, so I'm more of a beginner and not very familiar with programming things. (I have some basic knowledge)

My problem: In Excel [A1:D1] should be 0 (or any other cells, it's an example)

My idea:

x = 97
position = chr(x)   str("1")
while x < 100:
   x  =1
   sheet[position].value = 0
   position = chr(x)   str("1")

Something like this, so I would loop until all the cells were reached. BUT is there an easier solution to this? I mean, that can't be the best way to do it. I imagine something more like:

sheet['A1':'D1'].value = 0

But then I get a tuple and can't assigne a value. I searched on SO and YouTube but it seems like nobody had talked about this problem yet. I really hope somebody can help me solve this.

CodePudding user response:

From the info provided, you are trying to open an Excel file using python openpyxl and update cells A1:D1 (in say Sheet1) with 0s. If that is the case, you can use this. Note that cell(row, column) will indicate the particular cell in excel

file = openpyxl.load_workbook("Myfile.xlsx",read_only=False)
mySheet = file["Sheet1"]
for col in range(1,5):
    mySheet.cell(1,col).value = 0
file.save("Myfile.xlsx")
file.close()
  • Related