Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't openpyxl recognize the name of a sheet in an existing excel file that I open?

I am using the following code to open an existing Excel file in python 3.6, Excel 2016:

Shnm = my_pyx.get_sheet_names() 
sheet = my_pyx.get_sheet_by_name(Shnm[0])

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.get_sheet_by_name(sheet)
        self.dest="destination.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)

source

So when I do:

row_dest=2
column_dest=6   
workbook = Copy_excel(my_file)
data=60
workbook.write_workbook(2,6,data )
workbook.save_excel()

where: my_file is a str like filename.xlsx and sheet is a str with the sheet name.

It bugs me with an error stating that the sheet name mentioned does not exist.

I also tried to replace:

self.ws = self.wb.get_sheet_by_name(sheet)

with

self.ws = self.wb[sheet]

but I still receive the same error.

like image 390
FabioSpaghetti Avatar asked Feb 28 '19 13:02

FabioSpaghetti


People also ask

How do I get the sheet name in Excel using openpyxl?

Step1: First Import the openpyxl library to the program. Step2: Load/Connect the Excel Workbook to the program. Step3: Use sheetnames property to get the names of all the sheets of the given workbook.


1 Answers

The problem was setting:

sheet = my_pyx.get_sheet_by_name(Shnm[0])

And later set:

self.ws = self.wb[sheet]

Since sheet is not the sheet name but the actual sheet object you should use:

self.ws = self.wb[Shnm[0]] 

I have tried this code and it worked for me:

from openpyxl import load_workbook
# Class to manage excel data with openpyxl.

class Copy_excel:
    def __init__(self,src):
        self.wb = load_workbook(src)
        Shnm = self.wb.sheetnames
        self.ws = self.wb[Shnm[0]]
        self.ws = self.wb[sheet]
        self.dest='path\\to\\Copy.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)

row_dest=2
column_dest=6
workbook = Copy_excel('path\\to\\file.xlsx')
data=60
workbook.write_workbook(2,6,data )
workbook.save_excel()
like image 163
Hawk59 Avatar answered Nov 14 '22 22:11

Hawk59