Writing data to Excel sheet with openpyxl does not work

Using openpyxl , I try to read data from an Excel-Workbook and write data to the same Excel-Workbook. Getting data from an Excel-Workbook works fine, but writing data to an Excel-Workbook does not work. Using the code below, I get the value from cell A1 to Sheet1 and print it. Then I try to put some values ​​in 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 wrong here?

+5
source share
2 answers

I believe that you are missing the save function. Try adding an extra 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") 
+8
source

Use this to write the 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 
-1
source

All Articles