How do I use openpyxl and still maintain OOP structure?

2024/10/15 1:21:44

I am using python to do some simulations and using openpyxl to generate the reports. Now the simulation is results are to be divided into several sheets of an excel file. By the principles of OOP my structure should have a base simulator class which implements basic operations and several derived classes which implement modifications to simulator. Since functions related to a class should remain with the class I want the report sheets to be generated by the derived classes (with all its styling and formatting etc). Then maybe a driver class or function which takes all these report sheets and puts them in one work book. But as far as I can tell there is no way to copy a worksheet in openpyxl. Now it seems like I have broken the OOP models. Is there a way out of this?

Edit

Here is an example for my code. This is a trimmed fat free version, the real class is not that simple

from openpyxl import Workbook
from openpyxl.styles import Fontclass sim1:#this will inherit from another class sim which has basic operationsdef __init__(self):#assume function calling and complex math hereself.x = 1def f1OverRide(self):#over rides some function in sim to implement custom method for sim1 (several of these)return 23def get_sheet(self):wb = Workbook()ws = wb.activews['A1'] = self.x#example formatting real formatting is pretty complexws['A1'].font = Font(size=12,name='Calibri')return wsclass sim2:#this will inherit from another class sim which has basic operationsdef __init__(self):#assume function calling and complex math hereself.x = 12def f1OverRide(self):#over rides some function in sim to implement custom method for sim1 (several of these)return 42def get_sheet(self):wb = Workbook()ws = wb.activews['A1'] = self.x#example formatting, real formatting is pretty complexws['A1'].font = Font(size=14,name='Calibri',color='ff2223')return wss1 = 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
Answer

OOP copy Worksheets between Workbooks, for instance:

from openpyxl import Workbook
from openpyxl.styles import Font
from copy import copyclass sim():def __init__(self, n):self.n = ndef get_sheet(self):#...wb = Workbook()ws = wb.activews['A1'] = 'sim'+str(self.n)if self.n == 1:ws['A1'].font = Font(size=12,name='Calibri')else:ws['A1'].font = Font(size=14, name='Calibri', color='ff2223')return wsclass sim_Workbook(Workbook):# overload Workbook.copy_worksheetdef copy_worksheet(self, from_worksheet):# Create new empty sheet and append it to self(Workbook)ws = self.create_sheet( title=from_worksheet.title )for row, row_data in enumerate(from_worksheet.rows,1):for column, from_cell in enumerate(row_data,1):cell = ws.cell(row=row, column=column)cell.value = from_cell.valuecell.font = copy(from_cell.font)
s1 = sim(1)
s2 = sim(2)wb = sim_Workbook()
wb.copy_worksheet( s1.get_sheet() )
wb.copy_worksheet( s2.get_sheet() )
wb.save('../test/test.xlsx')  

#example formatting real formatting is pretty complex

You have to copy your complex formatting, style by style as shown by font in the example. This could lead to huge workload, depending how many cells you have to copy.
Read this to get a hint about this, but you can't do it 1:1 as you copy from workbook to workbook copying-styles-from-a-range-to-another-range

Tested with Python:3.4.2 - openpyxl:2.4.1 - LibreOffice: 4.3.3.2

https://en.xdnf.cn/q/117888.html

Related Q&A

Leaving rows with a giving value in column

UPDATED: In my dataset I have 3 columns (x,y) and VALUE. Its looking like this(sorted already):df1: x , y ,value 1 , 1 , 12 2 , 2 , 12 4 , 3 , 12 1 , 1 , 11 2 , 2 , 11 4 , 3 , 11 1 , 1 , 33 2 , 2 , 33 …

Python Circular dependencies, unable to link variable to other file

I am working on a program that allows me to directly edit a word document through a tkinter application. I am trying to link the tkinter input from my gui file to my main file so that I can execute my …

how to use xlrd module with python for abaqus

Im working on a script for abaqus where I have to import data from an excel file to put them into my script. I already downloaded the xlrd module and it work well on python interpreter (IDLE), but when…

Property in Python with @property.getter

I have an intresting behaviour for the following code:class MyClass:def __init__(self):self.abc = 10@propertydef age(self):return self.abc@age.getterdef age(self):return self.abc + 10@age.setterdef age…

Foreign Key Access

--------------------------------------------MODELS.PY-------------------------------------------- class Artist(models.Model):name = models.CharField("artist", max_length=50) #will display &…

ValueError: could not broadcast input array from shape (22500,3) into shape (1)

I relied on the code mentioned, here, but with minor edits. The version that I have is as follows:import numpy as np import _pickle as cPickle from PIL import Image import sys,ospixels = [] labels = []…

VGG 16/19 Slow Runtimes

When I try to get an output from the pre-trained VGG 16/19 models using Caffe with Python (both 2.7 and 3.5) its taking over 15 seconds on the net.forward() step (on my laptops CPU).I was wondering if …

Numpy vs built-in copy list

what is the difference below codesbuilt-in list code>>> a = [1,2,3,4] >>> b = a[1:3] >>> b[1] = 0 >>> a [1, 2, 3, 4] >>> b [2, 0]numpy array>>> c …

Scrapy returns only first result

Im trying to scrape data from gelbeseiten.de (yellow pages in germany)# -*- coding: utf-8 -*- import scrapyfrom scrapy.spiders import CrawlSpiderfrom scrapy.http import Requestfrom scrapy.selector impo…

Softlayer getAllBillingItems stopped working?

The following python script worked like a charm last month:Script:import SoftLayer client = SoftLayer.Client(username=someUser, api_key=someKey) LastInvoice = client[Account].getAllBillingItems() print…