Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/66065624/edit-excel-file-with-openpyxl-using-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...