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

标签 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]

但我仍然收到同样的错误。

最佳答案

问题在于设置:

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()

关于python - 为什么 openpyxl 无法识别我打开的现有 Excel 文件中的工作表名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54927298/

相关文章:

excel - 隐藏包含的单元格

python - 我的 python 脚本中的枚举没有按预期工作?

python - 如何将值列表中的多个项目输入到电子表格中

python - 如何在从 pandas 读取 excel 文件时以编程方式找出正确的标题?

python - 错误 : "No module named _markerlib" when installing some packages on virtualenv

python - 单元测试 : assert exception-handling function called

python - 将值添加到列表并将类型更改为 int

excel - 从公式运行的宏不会复制/粘贴,但通过 vbe 运行它可以正常工作

excel - Oracle ODBC TNS-less 连接字符串(适用于 64 位 Excel)

python - 内存中列表的大小