Home > OS >  How to insert a value to a specific cell in an existing excel file in Python?
How to insert a value to a specific cell in an existing excel file in Python?

Time:06-26

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. enter image description here

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.

CodePudding user response:

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

enter image description here

  • Related