[英]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.使用
openpyxl
,我正在尝试从 Excel-Workbook 读取数据并将数据写入同一个 Excel-Workbook。 Getting data from the Excel-Workbook works fine, but writing data into the Excel-Workbook does not work.从 Excel-Workbook 获取数据工作正常,但将数据写入 Excel-Workbook 不起作用。 With the code below I get the value from Cell
A1
in Sheet1
and print it.使用下面的代码,我从
Sheet1
的单元格A1
中获取值并打印它。 Then I try to put some values into the cells A2
and A3
.然后我尝试将一些值放入单元格
A2
和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")
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
while saving the workbook, try giving the full path.在保存工作簿时,尝试提供完整路径。 for example:
wb1.save(filename=r"C:\Users\7000027842\Downloads\test.xlsx")
例如:
wb1.save(filename=r"C:\Users\7000027842\Downloads\test.xlsx")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.