为什么openpyxl无法识别我打开的现有excel文件中工作表的名称?

时间:2019-02-28 13:51:37

标签: python excel openpyxl

我正在使用以下代码在python 3.6,Excel 2016中打开现有的Excel文件:

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

所以当我这样做时:

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

其中: my_file是类似于filename.xlsx的str,sheet是具有工作表名称的str。

它使我烦恼,并指出该工作表名称不存在。

我也尝试替换:

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

使用

self.ws = self.wb[sheet]

但是我仍然收到相同的错误。

1 个答案:

答案 0 :(得分:1)

问题出在以下地方:

sheet = my_pyx.get_sheet_by_name(Shnm[0])

然后设置:

self.ws = self.wb[sheet]

由于工作表不是工作表名称,而是您应使用的实际工作表对象:

self.ws = self.wb[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)
        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()