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

空扰寡人 提交于 2019-12-01 02:12:14

问题


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?


回答1:


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")



回答2:


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 


来源:https://stackoverflow.com/questions/29901558/writing-data-into-excel-sheet-using-openpyxl-isnt-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!