[英]How to insert a value to a specific cell in an existing excel file in Python?
As you can see in the following image, I am trying to insert the string "Latest Price" to cell D1 in an existing sheet "new_sheet" in an excel file.正如您在下图中看到的那样,我正在尝试将字符串“最新价格”插入到 Excel 文件中现有工作表“new_sheet”中的单元格 D1 中。
My code is as follows.我的代码如下。
import pandas as pd
import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
file_source =r'C:\Users\user\Desktop\Data.xlsx'
df = pd.read_excel(file_source)
#load excel file
workbook = load_workbook(filename=file_source)
#Read the sheet "new_sheet"
ws4 = workbook["new_sheet"]
#open workbook
sheet = ws4.active
#modify the desired cell
sheet["D1"] = 'Latest Price'
#save the file
workbook.save(filename=file_source)
However, it showed the following error.但是,它显示了以下错误。
AttributeError: 'Worksheet' object has no attribute 'active'
I can not find the cause for the error.我找不到错误的原因。 Please help me find it.请帮我找到它。
you can update a single cell using the cell.value
in openpyxl
.您可以使用cell.value
中的openpyxl
更新单个单元格。 The code is updated as below.代码更新如下。 Let me know in case of issues.如有问题请告诉我。
import pandas as pd
from openpyxl import load_workbook
file_source =r'C:\Users\user\Desktop\Micron_Baseline Cleanup\Data.xlsx'
#load excel file
workbook = load_workbook(filename=file_source)
#Pick the sheet "new_sheet"
ws4 = workbook["new_sheet"]
#modify the desired cell
ws4.cell(row = 1, column = 4).value = 'Latest Price'
#save the file
workbook.save(filename=file_source)
Output excel after running the code运行代码后输出excel
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.