使用openpyxl将数据写入Excel-Sheet不起作用 [英] Writing data into Excel-Sheet using openpyxl isn't working
问题描述
使用openpyxl
,我试图从Excel工作簿中读取数据并将数据写入到同一Excel工作簿中.从Excel-Workbook中获取数据可以正常工作,但是将数据写入Excel-Workbook中是行不通的.使用下面的代码,我从Sheet1
中的单元格A1
获取值并将其打印出来.然后,我尝试将一些值放入单元格A2
和A3
中.这是行不通的.
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?
推荐答案
我相信您缺少保存功能.尝试在下面添加其他行.
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")
这篇关于使用openpyxl将数据写入Excel-Sheet不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!