How Do I Use Openpyxl And Still Maintain Oop Structure?
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 pr
Solution 1:
OOP copy Worksheets between Workbooks, for instance:
from openpyxl import Workbook
from openpyxl.styles import Font
from copy import copy
classsim():
def__init__(self, n):
self.n = n
defget_sheet(self):
#...
wb = Workbook()
ws = wb.active
ws['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 ws
classsim_Workbook(Workbook):
# overload Workbook.copy_worksheetdefcopy_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 inenumerate(from_worksheet.rows,1):
for column, from_cell inenumerate(row_data,1):
cell = ws.cell(row=row, column=column)
cell.value = from_cell.value
cell.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 workbookcopying-styles-from-a-range-to-another-range
Tested with Python:3.4.2 - openpyxl:2.4.1 - LibreOffice: 4.3.3.2
Post a Comment for "How Do I Use Openpyxl And Still Maintain Oop Structure?"