steady_progress
steady_progress

Reputation: 3741

Writing data into Excel-Sheet using openpyxl isn't working

Using openpyxl, I am trying to read data from an Excel-Workbook and write data to this same Excel-Workbook. Getting data from the Excel-Workbook works fine, but writing data into the Excel-Workbook does not work. With the code below I get the value from Cell A1 in Sheet1 and print it. Then I try to put some values into the cells A2 and A3. This does not work.

from openpyxl import Workbook
from openpyxl import load_workbook


wb = load_workbook("testexcel.xlsm")
ws1 = wb.get_sheet_by_name("Sheet1")

#This works:
print ws1.cell(row=1, column=1).value 

#This doesn't work:
ws1['A2'] = "SomeValue1"

#This doesn't work either:
ws1.cell(row=3, column=1).value = "SomeValue2"

I am sure the code is correct ... What is going wrong here?

Upvotes: 10

Views: 34982

Answers (3)

while saving the workbook, try giving the full path. for example: wb1.save(filename=r"C:\Users\7000027842\Downloads\test.xlsx")

Upvotes: 0

Abul
Abul

Reputation: 71

Use this to write a value:

ws1.cell(row=1, column=1,value='Hey')

On the other hand, the following will read the value:

ws1.cell(row=1, column=1).value 

Upvotes: 6

Woodsy
Woodsy

Reputation: 3377

I believe you are missing a save function. Try adding the additional line below.

from openpyxl import Workbook
from openpyxl import load_workbook


wb = load_workbook("testexcel.xlsm")
ws1 = wb.get_sheet_by_name("Sheet1")

#This works:
print ws1.cell(row=1, column=1).value 

#This doesn't work:
ws1['A2'] = "SomeValue1"

#This doesn't work either:
ws1.cell(row=3, column=1).value = "SomeValue2"

#Add this line
wb.save("testexcel.xlsm")

Upvotes: 20

Related Questions