Python 使用 openpyxl 将数据写入 Excel-Sheet 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29901558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:09:04  来源:igfitidea点击:

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

pythonexcelopenpyxl

提问by steady_progress

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 A1in Sheet1and print it. Then I try to put some values into the cells A2and A3. This does not work.

使用openpyxl,我试图从 Excel 工作簿读取数据并将数据写入同一个 Excel 工作簿。从 Excel-Workbook 获取数据工作正常,但将数据写入 Excel-Workbook 不起作用。使用下面的代码,我从 Cell A1in 中获取值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"

I am sure the code is correct ... What is going wrong here?

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

采纳答案by Woodsy

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

回答by Abul

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