繁体   English   中英

如何在 Python 中现有的 excel 文件中向特定单元格插入值?

[英]How to insert a value to a specific cell in an existing excel file in Python?

正如您在下图中看到的那样,我正在尝试将字符串“最新价格”插入到 Excel 文件中现有工作表“new_sheet”中的单元格 D1 中。 在此处输入图像描述

我的代码如下。

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)

但是,它显示了以下错误。

AttributeError: 'Worksheet' object has no attribute 'active'

我找不到错误的原因。 请帮我找到它。

您可以使用cell.value中的openpyxl更新单个单元格。 代码更新如下。 如有问题请告诉我。

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)

运行代码后输出excel

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM