使用openpyxl
,我试图从Excel工作簿中读取数据并将数据写入同一个Excel工作簿。从Excel-Workbook获取数据工作正常,但将数据写入Excel-Workbook不起作用。使用下面的代码,我从A1
中的单元格Sheet1
获取值并打印出来。然后我尝试将一些值放入单元格A2
和A3
。这不起作用。
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"
我确信代码是正确的......这里出了什么问题?
答案 0 :(得分:10)
我相信你错过了保存功能。尝试添加以下附加行。
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")
答案 1 :(得分:1)
用它来写一个值:
ws1.cell(row=1, column=1,value='Hey')
另一方面,以下内容将读取值:
ws1.cell(row=1, column=1).value