Skip to content
Advertisement

Edit excel file with openpyxl using Python

I have an excel file which I want to edit to include new datas and diagrams.

I’m using this code :

from openpyxl import load_workbook

# Class to manage excel data with openpyxl
class Copy_Excel:
    def __init__(self, src):
        self.wb = load_workbook(src)
        self.ws = self.wb["Sheet1"]
        self.dest="test.xlsx"
    
    # Write the value in the cell defined by row_dest+column_dest         
    def write_workbook(self,row_dest,column_dest,value):
        c = self.ws.cell(row = row_dest, column = column_dest)
        c.value = value

    # Save excel file
    def save_excel(self) :  
        self.wb.save(self.dest)

test = Copy_Excel("C:/pathToFile/test.xlsx")
    
test.write_workbook(5, 3, 100000)

test.save_excel()

The execution went fine but nothing happened.

Advertisement

Answer

It was not a problem with python or the program itself.

It was about the position in the terminal where you execute the program.

If you write your path as :

"myfile.xlsx"

your terminal has to be in the folder where your loaded excel file is.

And not to be confused with : “yes it should work if you put your excel file in the same folder as the .py file that you will execute.”

So the answer was to put the full path like that :

"C:/myfullpath/toThe/file.xlsx"

or to use the cd command to move in the same folder (or working directory) as your excel file, from your terminal.

Otherwise, the function I wrote above is working well, and can help if you have to read, and edit an excel file with the openpyxl module using python.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement