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?
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
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With