I am trying to style and write excel files dynamically. Here is my code
import pandas as pd
import copy
class OutputWriter(object):
def __init__(self, fmt_func, sheet_name='data'):
'''
Initializing...
'''
# NOTICE: Initialising with path set None since I do not know path yet
wrt = pd.ExcelWriter(None, engine='xlsxwriter')
self._writer = fmt_func(wrt, sheet_name)
self._sheet_name = sheet_name
def save(self, df, o_path):
'''
Save the file to a path
'''
# setting path in writer before saving
self._writer.path = o_path
df.to_excel(self._writer, sheet_name=self._sheet_name)
self._writer.save()
# Change first row color to blue
def fmt_func_blue(wrt, sheet_name):
# ERROR Cannot clone `wrt` path is not set
writer = copy.deepcopy(wrt)
sheet = writer.sheets[sheet_name]
workbook = writer.book
# Proceed to color first row blue
header_fmt = workbook.add_format({
'text_wrap': True,
'bg_color': '#191970',
'font_color': '#FFFFFF',
})
header_fmt.set_align('center')
header_fmt.set_align('vcenter')
sheet.set_row(0, None, header_fmt)
return writer
# Change first row color to red
def fmt_func_red(wrt, sheet_name):
writer = copy.deepcopy(wrt)
# I haven't saved the excel file so there are no sheets
sheet = writer.sheets[sheet_name]
workbook = writer.book
# Proceed to color first row red
header_fmt = workbook.add_format({
'text_wrap': True,
'bg_color': '#FF2200',
'font_color': '#FFFFFF',
})
header_fmt.set_align('center')
header_fmt.set_align('vcenter')
sheet.set_row(0, None, header_fmt)
return writer
writer_red = OutputWriter(fmt_func_red, sheet_name='red')
writer_blue = OutputWriter(fmt_func_blue, sheet_name='blue')
I have two issues:
1) I can't clone the xlwriter object in my styling function
2) There are no sheets in my workbook at the time I try to style the excel files.
Is there any way I can make this work?
fmt_func_red
usesself
inside but it is not passed in function. Please create a reproducible version which one can directly run – Groundnut