Add int value in a cell of excel file from python code

653 views Asked by At

My excel file contains multiple sheets, I am trying to add value(int:5) in cell("C5") in sheet("sheet_1") of excel file("testexcel.xlsx"). I tried many ways, but none of the functions are able to edit the excel file. Excel File either gets corrupted or no changes are seen. Could you please suggest a way? Thank you! Note: https://www.geeksforgeeks.org/change-value-in-excel-using-python/ tried this methods

2

There are 2 answers

0
Redox On BEST ANSWER

As suggested by Charlie Clark, if you want to use openpyxl, you can use the below code...

import openpyxl
wb = openpyxl.load_workbook("testexcel.xlsx")
ws = wb["sheet_1"]
val = 5 # Giving it separately in case you are getting this from another part of your program
ws.cell(row=5, column=3).value = val #column C is the 3rd column
wb.save("testexcel.xlsx")
3
Marco Frag Delle Monache On

You can use pandas! It's a great library that does exactly this. I'll give you a quick example on how it works.

import pandas

file_path = "/path/to/file.xls"
file = open(file_path, "r")
xlsx = pandas.ExcelFile(file.name)
sheets = xlsx.sheet_names
sheet = sheets[0] # you can choose which sheet to work on
sheet.iloc[1][0] # you can access cells by indexing row and column
# code here to write a new xls with updated values in cells

This is a great guide you can follow!