【发布时间】:2017-03-15 22:32:07
【问题描述】:
我正在使用 python 进行一些模拟并使用 openpyxl 生成报告。现在模拟结果将被分成几张excel文件。根据 OOP 的原则,我的结构应该有一个实现基本操作的基本模拟器类和几个实现对模拟器修改的派生类。由于与类相关的函数应保留在类中,因此我希望由派生类生成报告表(及其所有样式和格式等)。然后可能是一个驱动程序类或函数,它将所有这些报告表放入一个工作簿中。但据我所知,没有办法在 openpyxl 中复制工作表。现在看来我已经打破了 OOP 模型。有没有办法解决这个问题?
编辑
这是我的代码示例。这是修剪过的脱脂版,真正的课没那么简单
from openpyxl import Workbook
from openpyxl.styles import Font
class sim1:#this will inherit from another class sim which has basic operations
def __init__(self):
#assume function calling and complex math here
self.x = 1
def f1OverRide(self):
#over rides some function in sim to implement custom method for sim1 (several of these)
return 23
def get_sheet(self):
wb = Workbook()
ws = wb.active
ws['A1'] = self.x
#example formatting real formatting is pretty complex
ws['A1'].font = Font(size=12,name='Calibri')
return ws
class sim2:#this will inherit from another class sim which has basic operations
def __init__(self):
#assume function calling and complex math here
self.x = 12
def f1OverRide(self):
#over rides some function in sim to implement custom method for sim1 (several of these)
return 42
def get_sheet(self):
wb = Workbook()
ws = wb.active
ws['A1'] = self.x
#example formatting, real formatting is pretty complex
ws['A1'].font = Font(size=14,name='Calibri',color='ff2223')
return ws
s1 = sim1()
s2 = sim2()
# now I want to get the sheets for sim1 and sim2 and combine in 1 workbook
wb = Workbook()
ws1 = s1.get_sheet()
ws2 = s2.get_sheet()
# dont know what to do now :( openpyxl can not copy sheet into this workbook
【问题讨论】:
-
无法发现问题,我总是将 OOP 与 openpyxl 一起使用。请提供一个小代码示例来说明您遇到的问题。
-
您可以在 openpyxl 中复制工作表,但只能在同一个工作簿中。