简体   繁体   English

使用 Python 使用 openpyxl 编辑 excel 文件

[英]Edit excel file with openpyxl using Python

I have an excel file which I want to edit to include new datas and diagrams.我有一个 excel 文件,我想对其进行编辑以包含新的数据和图表。

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.执行很顺利,但什么也没发生。

It was not a problem with python or the program itself. python 或程序本身没有问题。

It was about the position in the terminal where you execute the program.这是关于您执行程序的终端中的 position 。

If you write your path as:如果您将路径写为:

"myfile.xlsx"

your terminal has to be in the folder where your loaded excel file is.您的终端必须位于您加载的 excel 文件所在的文件夹中。

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."不要混淆:“是的,如果您将 excel 文件放在与您将执行的 .py 文件相同的文件夹中,它应该可以工作。”

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.或使用 cd 命令从终端移入与 excel 文件相同的文件夹(或工作目录)。

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.否则,我在上面写的 function 运行良好,如果您必须阅读并使用 python 使用 openpyxl 模块编辑 excel 文件,它可以提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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