使用openpyxl,我试图从Excel工作簿中读取数据并将数据写入到同一Excel工作簿中。从Excel-Workbook中获取数据可以正常工作,但是将数据写入Excel-Workbook中不起作用。使用下面的代码,我从A1中的Cell Sheet1中获取值并将其打印出来。然后,我尝试将一些值放入A2A3单元格中。这是行不通的。

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"

我确定代码正确无误...这里出了什么问题?

最佳答案

我相信您缺少保存功能。尝试在下面添加其他行。

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

08-24 20:07