简体   繁体   中英

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. 在此处输入图像描述

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 . 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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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