Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 540
steady_progress Avatar asked Apr 27 '15 16:04

steady_progress


2 Answers

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 
like image 75
Abul Avatar answered Oct 06 '22 19:10

Abul


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")
like image 42
Woodsy Avatar answered Oct 06 '22 19:10

Woodsy