def _process_style(self, style: dict[str, Any]) -> str: """Convert a style dictionary to a OpenDocument style sheet Parameters ---------- style : Dict Style dictionary Returns ------- style_key : str Unique style key for later reference in sheet """ from odf.style import ( ParagraphProperties, Style, TableCellProperties, TextProperties, ) if style is None: return None style_key = json.dumps(style) if style_key in self._style_dict: return self._style_dict[style_key] name = f"pd{len(self._style_dict)+1}" self._style_dict[style_key] = name odf_style = Style(name=name, family="table-cell") if "font" in style: font = style["font"] if font.get("bold", False): odf_style.addElement(TextProperties(fontweight="bold")) if "borders" in style: borders = style["borders"] for side, thickness in borders.items(): thickness_translation = {"thin": "0.75pt solid #000000"} odf_style.addElement( TableCellProperties( attributes={ f"border{side}": thickness_translation[thickness] })) if "alignment" in style: alignment = style["alignment"] horizontal = alignment.get("horizontal") if horizontal: odf_style.addElement(ParagraphProperties(textalign=horizontal)) vertical = alignment.get("vertical") if vertical: odf_style.addElement( TableCellProperties(verticalalign=vertical)) self.book.styles.addElement(odf_style) return name
def create_blank_ods_with_styles(): """Create a dmutils.ods.SpreadSheet pre-configured with some default styles, ready for population with data appropriate for the subclass View. Modifications here (except adding styles) are likely breaking changes.""" spreadsheet = ods.SpreadSheet() # Add the font we will use for the entire spreadsheet. spreadsheet.add_font(FontFace(name="Arial", fontfamily="Arial")) # Add some default styles for columns. spreadsheet.add_style("col-default", "table-column", ( TableColumnProperties(breakbefore="auto"), ), parentstylename="Default") spreadsheet.add_style("col-wide", "table-column", ( TableColumnProperties(columnwidth="150pt", breakbefore="auto"), ), parentstylename="Default") spreadsheet.add_style("col-extra-wide", "table-column", ( TableColumnProperties(columnwidth="300pt", breakbefore="auto"), ), parentstylename="Default") # Add some default styles for rows. spreadsheet.add_style("row-default", "table-row", ( TableRowProperties(breakbefore="auto", useoptimalrowheight="false"), ), parentstylename="Default") spreadsheet.add_style("row-tall", "table-row", ( TableRowProperties(breakbefore="auto", rowheight="30pt", useoptimalrowheight="false"), ), parentstylename="Default") spreadsheet.add_style("row-tall-optimal", "table-row", ( TableRowProperties(breakbefore="auto", rowheight="30pt", useoptimalrowheight="true"), ), parentstylename="Default") # Add some default styles for cells. spreadsheet.add_style("cell-default", "table-cell", ( TableCellProperties(wrapoption="wrap", verticalalign="top"), TextProperties(fontfamily="Arial", fontnameasian="Arial", fontnamecomplex="Arial", fontsize="11pt"), ), parentstylename="Default") spreadsheet.add_style("cell-header", "table-cell", ( TableCellProperties(wrapoption="wrap", verticalalign="top"), TextProperties(fontfamily="Arial", fontnameasian="Arial", fontnamecomplex="Arial", fontsize="11pt", fontweight="bold"), ), parentstylename="Default") return spreadsheet
def getStyle(self, c, cell, datastylename, style_id, odfdoc): ''' get a style_name by style_id ''' if not style_id in list(self.styles.keys()): # create new style cs = Style(name = cell, family = 'table-cell', datastylename=datastylename) cs.addElement(TextProperties(color = c.color, fontsize =c.font_size, fontfamily = c.font_family)) # set backgound and borders if c.background_color != "default" and c.background_color != "transparent": cs.addElement(TableCellProperties(backgroundcolor = c.background_color)) if c.border_top != "none": cs.addElement(TableCellProperties(bordertop = c.border_top)) if c.border_bottom != "none": cs.addElement(TableCellProperties(borderbottom = c.border_bottom)) if c.border_left != "none": cs.addElement(TableCellProperties(borderleft = c.border_left)) if c.border_right != "none": cs.addElement(TableCellProperties(borderright = c.border_right)) # set ods conditional style if (c.condition): cns = Style(name = "cns"+cell, family = 'table-cell') cns.addElement(TextProperties(color = c.condition_color)) cns.addElement(TableCellProperties(backgroundcolor = c.condition_background_color)) odfdoc.styles.addElement(cns) cs.addElement(Map(condition = c.condition, applystylename = "cns"+cell)) odfdoc.automaticstyles.addElement(cs) self.styles[style_id] = cell return self.styles[style_id]
def __init__(self): self.doc = OpenDocumentSpreadsheet() #styles self.itemRowStyle1 = Style(name="itemRowStyle", family="table-row") self.itemRowStyle1.addElement(TableRowProperties(rowheight="7mm")) self.doc.automaticstyles.addElement(self.itemRowStyle1) self.itemRowStyle3 = Style(name="itemRowStyle", family="table-row") self.itemRowStyle3.addElement(TableRowProperties(rowheight="30mm")) self.doc.automaticstyles.addElement(self.itemRowStyle3) self.colStyle30 = Style(name="colStyle30", family="table-column") self.colStyle30.addElement(TableColumnProperties(columnwidth="25mm")) self.doc.automaticstyles.addElement(self.colStyle30) self.colStyle40 = Style(name="colStyle40", family="table-column") self.colStyle40.addElement(TableColumnProperties(columnwidth="40mm")) self.doc.automaticstyles.addElement(self.colStyle40) self.colStyle50 = Style(name="colStyle50", family="table-column") self.colStyle50.addElement(TableColumnProperties(columnwidth="50mm")) self.doc.automaticstyles.addElement(self.colStyle50) self.colStyle200 = Style(name="colStyle200", family="table-column") self.colStyle200.addElement(TableColumnProperties(columnwidth="200mm")) self.doc.automaticstyles.addElement(self.colStyle200) self.cellStyle1 = Style(name="cellStyle1",family="table-cell", parentstylename='Standard', displayname="middle") self.cellStyle1.addElement(ParagraphProperties(textalign="center")) self.cellStyle1.addElement(TableCellProperties(verticalalign="middle")) self.cellStyle1.addElement(TableCellProperties(wrapoption="wrap")) self.doc.automaticstyles.addElement(self.cellStyle1) self.hdrStyle = Style(name="hdrStyle",family="table-cell", parentstylename='Standard', displayname="middle") self.hdrStyle.addElement(ParagraphProperties(textalign="center")) self.hdrStyle.addElement(TextProperties(fontweight="bold")) self.hdrStyle.addElement(TableCellProperties(verticalalign="middle")) self.doc.automaticstyles.addElement(self.hdrStyle)
def write(self): super().write() self.doc = OpenDocumentSpreadsheet() self.cell_formats = {} for key, value in self.colours.items(): style = Style(name=key, family="table-cell") style.addElement(TableCellProperties(backgroundcolor="#" + value)) self.doc.automaticstyles.addElement(style) self.cell_formats[key] = style for sheet in self.sheets: self.write_table(sheet) self.doc.save(self.filename, True)
def init(LOdoc, numfonts=1): totalwid = 6800 #6.8inches #compute column widths f = min(numfonts,4) ashare = 4*(6-f) dshare = 2*(6-f) bshare = 100 - 2*ashare - dshare awid = totalwid * ashare // 100 dwid = totalwid * dshare // 100 bwid = totalwid * bshare // (numfonts * 100) # create styles for table, for columns (one style for each column width) # and for one cell (used for everywhere except where background changed) tstyle = Style(name="Table1", family="table") tstyle.addElement(TableProperties(attributes={'width':str(totalwid/1000.)+"in", 'align':"left"})) LOdoc.automaticstyles.addElement(tstyle) tastyle = Style(name="Table1.A", family="table-column") tastyle.addElement(TableColumnProperties(attributes={'columnwidth':str(awid/1000.)+"in"})) LOdoc.automaticstyles.addElement(tastyle) tbstyle = Style(name="Table1.B", family="table-column") tbstyle.addElement(TableColumnProperties(attributes={'columnwidth':str(bwid/1000.)+"in"})) LOdoc.automaticstyles.addElement(tbstyle) tdstyle = Style(name="Table1.D", family="table-column") tdstyle.addElement(TableColumnProperties(attributes={'columnwidth':str(dwid/1000.)+"in"})) LOdoc.automaticstyles.addElement(tdstyle) ta1style = Style(name="Table1.A1", family="table-cell") ta1style.addElement(TableCellProperties(attributes={'padding':"0.035in", 'border':"0.05pt solid #000000"})) LOdoc.automaticstyles.addElement(ta1style) # text style used with non-<em> text t1style = Style(name="T1", family="text") t1style.addElement(TextProperties(attributes={'color':"#999999" })) LOdoc.automaticstyles.addElement(t1style) # create styles for Title, Subtitle tstyle = Style(name="Title", family="paragraph") tstyle.addElement(TextProperties(attributes={'fontfamily':"Arial",'fontsize':"24pt",'fontweight':"bold" })) LOdoc.styles.addElement(tstyle) ststyle = Style(name="Subtitle", family="paragraph") ststyle.addElement(TextProperties(attributes={'fontfamily':"Arial",'fontsize':"18pt",'fontweight':"bold" })) LOdoc.styles.addElement(ststyle)
})) h3style.addElement( ParagraphProperties(breakbefore="page", marginleft="0cm", marginright="0cm", margintop="0.2cm", marginbottom="0.2cm", lineheight="150%", textindent="1.2cm", autotextindent="false")) textdoc.automaticstyles.addElement(h3style) TAB_style = Style(name="Table", family="table-cell", parentstylename="Standard") TAB_style.addElement(TableCellProperties(border="0.05pt solid #000000")) textdoc.automaticstyles.addElement(TAB_style) TAB_stylered = Style(name="Table red", family="table-cell", parentstylename="Standard") TAB_stylered.addElement( TableCellProperties(backgroundcolor="ff0000", border="0.05pt solid #000000")) textdoc.automaticstyles.addElement(TAB_stylered) tableheaders = Style(name="Table Headers", family="paragraph", parentstylename="Standard") tableheaders.addElement( ParagraphProperties(numberlines="false",
def doit(args): logfile = args.logger if args.report: logfile.loglevel = args.report try: root = ET.parse(args.input).getroot() except: logfile.log("Error parsing FTML input", "S") if args.font: # font(s) specified on command line fontlist = getfonts(args.font, logfile) else: # get font spec from FTML fontsrc element fontlist = getfonts([root.find("./head/fontsrc").text], logfile, False) #fontlist = getfonts( [fs.text for fs in root.findall("./head/fontsrc")], False ) ### would allow multiple fontsrc elements numfonts = len(fontlist) if numfonts == 0: logfile.log("No font(s) specified", "S") if numfonts > 1: formattedfontnum = ["{0:02d}".format(n) for n in range(numfonts)] else: formattedfontnum = [""] logfile.log("Font(s) specified:", "V") for n, (fontname, bold, italic, embeddedfont) in enumerate(fontlist): logfile.log( " " + formattedfontnum[n] + " " + fontname + BoldItalic(bold, italic) + " " + str(embeddedfont), "V") # get optional fontscale; compute pointsize as int(12*fontscale/100). If result xx is not 12, then add "fo:font-size=xxpt" in Px styles pointsize = 12 fontscaleel = root.find("./head/fontscale") if fontscaleel != None: fontscale = fontscaleel.text try: pointsize = int(int(fontscale) * 12 / 100) except ValueError: # any problem leaves pointsize 12 logfile.log("Problem with fontscale value; defaulting to 12 point", "W") # Get FTML styles and generate LO writer styles # P2 is paragraph style for string element when no features specified # each Px (for P3...) corresponds to an FTML style, which specifies lang or feats or both # if numfonts > 1, two-digit font number is appended to make an LO writer style for each FTML style + font combo # When LO writer style is used with attribute rtl="True", "R" appended to style name LOstyles = {} ftmlstyles = {} Pstylenum = 2 LOstyles["P2"] = ("", None, None) ftmlstyles[0] = "P2" for s in root.findall("./head/styles/style"): Pstylenum += 1 Pnum = "P" + str(Pstylenum) featstring = "" if s.get('feats'): featstring = parsefeats(s.get('feats')) langname = None countryname = None lang = s.get('lang') if lang != None: x = re.match(langcode, lang) langname = x.group('langname') countryname = x.group('countryname') # FTML <test> element @stylename attribute references this <style> element @name attribute ftmlstyles[s.get('name')] = Pnum LOstyles[Pnum] = (featstring, langname, countryname) # create LOwriter file and construct styles for tables, column widths, etc. LOdoc = OpenDocumentText() init(LOdoc, numfonts) # Initialize sequence counters sds = SequenceDecls() sd = sds.addElement( SequenceDecl(displayoutlinelevel='0', name='Illustration')) sd = sds.addElement(SequenceDecl(displayoutlinelevel='0', name='Table')) sd = sds.addElement(SequenceDecl(displayoutlinelevel='0', name='Text')) sd = sds.addElement(SequenceDecl(displayoutlinelevel='0', name='Drawing')) LOdoc.text.addElement(sds) # Create Px style for each (featstring, langname, countryname) tuple in LOstyles # and for each font (if >1 font, append to Px style name a two-digit number corresponding to the font in fontlist) # and (if at least one rtl attribute) suffix of nothing or "R" # At the same time, collect info for creating FontFace elements (and any embedded fonts) suffixlist = ["", "R" ] if root.find(".//test/[@rtl='True']") != None else [""] fontfaces = {} for p in sorted(LOstyles, key=lambda x: int(x[1:]) ): # key = lambda x : int(x[1:]) corrects sort order featstring, langname, countryname = LOstyles[p] for n, (fontname, bold, italic, embeddedfont) in enumerate( fontlist): # embeddedfont = None if no embedding needed fontnum = formattedfontnum[n] # Collect fontface info: need one for each font family + feature combination # Put embedded font in list only under fontname with empty featstring if (fontname, featstring) not in fontfaces: fontfaces[(fontname, featstring)] = [] if embeddedfont: if (fontname, "") not in fontfaces: fontfaces[(fontname, "")] = [] if embeddedfont not in fontfaces[(fontname, "")]: fontfaces[(fontname, "")].append(embeddedfont) # Generate paragraph styles for s in suffixlist: pstyle = Style(name=p + fontnum + s, family="paragraph") if s == "R": pstyle.addElement( ParagraphProperties(textalign="end", justifysingleword="false", writingmode="rl-tb")) pstyledic = {} pstyledic['fontnamecomplex'] = \ pstyledic['fontnameasian'] =\ pstyledic['fontname'] = fontname + featstring pstyledic['fontsizecomplex'] = \ pstyledic['fontsizeasian'] = \ pstyledic['fontsize'] = str(pointsize) + "pt" if bold: pstyledic['fontweightcomplex'] = \ pstyledic['fontweightasian'] = \ pstyledic['fontweight'] = 'bold' if italic: pstyledic['fontstylecomplex'] = \ pstyledic['fontstyleasian'] = \ pstyledic['fontstyle'] = 'italic' if langname != None: pstyledic['languagecomplex'] = \ pstyledic['languageasian'] = \ pstyledic['language'] = langname if countryname != None: pstyledic['countrycomplex'] = \ pstyledic['countryasian'] = \ pstyledic['country'] = countryname pstyle.addElement(TextProperties(attributes=pstyledic)) # LOdoc.styles.addElement(pstyle) ### tried this, but when saving the generated odt, LO changed them to automatic styles LOdoc.automaticstyles.addElement(pstyle) fontstoembed = [] for fontname, featstring in sorted( fontfaces ): ### Or find a way to keep order of <style> elements from original FTML? ff = FontFace(name=fontname + featstring, fontfamily=fontname + featstring, fontpitch="variable") LOdoc.fontfacedecls.addElement(ff) if fontfaces[(fontname, featstring)]: # embedding needed for this combination for fontfile in fontfaces[(fontname, featstring)]: fontstoembed.append(fontfile) # make list for embedding ffsrc = FontFaceSrc() ffuri = FontFaceUri( **{ 'href': "Fonts/" + os.path.basename(fontfile), 'type': "simple" }) ffformat = FontFaceFormat(**{'string': 'truetype'}) ff.addElement(ffsrc) ffsrc.addElement(ffuri) ffuri.addElement(ffformat) basename = "Table1.B" colorcount = 0 colordic = { } # record color #rrggbb as key and "Table1.Bx" as stylename (where x is current color count) tablenum = 0 # get title and comment and use as title and subtitle titleel = root.find("./head/title") if titleel != None: LOdoc.text.addElement( H(outlinelevel=1, stylename="Title", text=titleel.text)) commentel = root.find("./head/comment") if commentel != None: LOdoc.text.addElement(P(stylename="Subtitle", text=commentel.text)) # Each testgroup element begins a new table for tg in root.findall("./testgroup"): # insert label attribute of testgroup element as subtitle tglabel = tg.get('label') if tglabel != None: LOdoc.text.addElement( H(outlinelevel=1, stylename="Subtitle", text=tglabel)) # insert text from comment subelement of testgroup element tgcommentel = tg.find("./comment") if tgcommentel != None: #print("commentel found") LOdoc.text.addElement(P(text=tgcommentel.text)) tgbg = tg.get( 'background') # background attribute of testgroup element tablenum += 1 table = Table(name="Table" + str(tablenum), stylename="Table1") table.addElement(TableColumn(stylename="Table1.A")) for n in range(numfonts): table.addElement(TableColumn(stylename="Table1.B")) table.addElement(TableColumn(stylename="Table1.A")) table.addElement(TableColumn(stylename="Table1.D")) for t in tg.findall("./test"): # Each test element begins a new row # stuff to start the row labeltext = t.get('label') stylename = t.get('stylename') stringel = t.find('./string') commentel = t.find('./comment') rtlsuffix = "R" if t.get('rtl') == 'True' else "" comment = commentel.text if commentel != None else None colBstyle = "Table1.A1" tbg = t.get( 'background' ) # get background attribute of test group (if one exists) if tbg == None: tbg = tgbg if tbg != None: # if background attribute for test element (or background attribute for testgroup element) if tbg not in colordic: # if color not found in color dic, create new style colorcount += 1 newname = basename + str(colorcount) colordic[tbg] = newname tb1style = Style(name=newname, family="table-cell") tb1style.addElement( TableCellProperties( attributes={ 'padding': "0.0382in", 'border': "0.05pt solid #000000", 'backgroundcolor': tbg })) LOdoc.automaticstyles.addElement(tb1style) colBstyle = colordic[tbg] row = TableRow() table.addElement(row) # fill cells # column A (label) cell = TableCell(stylename="Table1.A1", valuetype="string") if labeltext: cell.addElement( P(stylename="Table_20_Contents", text=labeltext)) row.addElement(cell) # column B (string) for n in range(numfonts): Pnum = ftmlstyles[stylename] if stylename != None else "P2" Pnum = Pnum + formattedfontnum[n] + rtlsuffix ### not clear if any of the following can be moved outside loop and reused cell = TableCell(stylename=colBstyle, valuetype="string") par = P(stylename=Pnum) if len(stringel) == 0: # no <em> subelements par.addText(re.sub(backu, hextounichr, stringel.text)) else: # handle <em> subelement(s) if stringel.text != None: par.addElement( Span(stylename="T1", text=re.sub(backu, hextounichr, stringel.text))) for e in stringel.findall("em"): if e.text != None: par.addText(re.sub(backu, hextounichr, e.text)) if e.tail != None: par.addElement( Span(stylename="T1", text=re.sub(backu, hextounichr, e.tail))) cell.addElement(par) row.addElement(cell) # column C (comment) cell = TableCell(stylename="Table1.A1", valuetype="string") if comment: cell.addElement(P(stylename="Table_20_Contents", text=comment)) row.addElement(cell) # column D (stylename) cell = TableCell(stylename="Table1.A1", valuetype="string") if comment: cell.addElement( P(stylename="Table_20_Contents", text=stylename)) row.addElement(cell) LOdoc.text.addElement(table) LOdoc.text.addElement(P(stylename="Subtitle", text="")) # Empty paragraph to end ### necessary? try: if fontstoembed: logfile.log("Embedding fonts in document", "V") for f in fontstoembed: LOdoc._extra.append( OpaqueObject( filename="Fonts/" + os.path.basename(f), mediatype= "application/x-font-ttf", ### should be "application/font-woff" or "/font-woff2" for WOFF fonts, "/font-opentype" for ttf content=io.open(f, "rb").read())) ci = ConfigItem(**{ 'name': 'EmbedFonts', 'type': 'boolean' }) ### (name = 'EmbedFonts', type = 'boolean') ci.addText('true') cis = ConfigItemSet(**{'name': 'ooo:configuration-settings' }) ### (name = 'ooo:configuration-settings') cis.addElement(ci) LOdoc.settings.addElement(cis) except: logfile.log("Error embedding fonts in document", "E") logfile.log("Writing output file: " + args.output, "P") LOdoc.save(unicode(args.output)) return
def write_report_ods(self, out_file: str, header_color: str = "#66ffff") -> None: """ Writes a report of all the events in the ics file as an ods. Is possible to optionally specify a background color for the header :param out_file (string): path for the output ods file :param header_color (string): background color for the header as hexadecimal (e.g. "#66ffff") """ textdoc = OpenDocumentSpreadsheet() table = Table(name="Events") # Header ceX = Style(name="ceX", family="table-cell") ceX.addElement( TableCellProperties(backgroundcolor=header_color, border="0.74pt solid #000000")) textdoc.styles.addElement(ceX) tr = TableRow() table.addElement(tr) cell = TableCell(valuetype="string", stylename="ceX") cell.addElement(P(text="title")) tr.addElement(cell) cell = TableCell(valuetype="string", stylename="ceX") cell.addElement(P(text="begin")) tr.addElement(cell) cell = TableCell(valuetype="string", stylename="ceX") cell.addElement(P(text="end")) tr.addElement(cell) cell = TableCell(valuetype="string", stylename="ceX") cell.addElement(P(text="duration")) tr.addElement(cell) cell = TableCell(valuetype="string", stylename="ceX") cell.addElement(P(text="description")) tr.addElement(cell) cell = TableCell(valuetype="string", stylename="ceX") cell.addElement(P(text="created")) tr.addElement(cell) cell = TableCell(valuetype="string", stylename="ceX") cell.addElement(P(text="location")) tr.addElement(cell) cell = TableCell(valuetype="string", stylename="ceX") cell.addElement(P(text="url")) tr.addElement(cell) # Content for ev in self.my_Calendar.events: tr = TableRow() (title, begin, end, duration, uid, description, created, location, url, transparent) = self.__get_fields__(ev) table.addElement(tr) cell = TableCell(valuetype="string") cell.addElement(P(text=title)) tr.addElement(cell) cell = TableCell() cell.addElement(P(text=begin.format('YYYY-MM-DD HH:mm:ss ZZ'))) tr.addElement(cell) cell = TableCell() cell.addElement(P(text=end.format('YYYY-MM-DD HH:mm:ss ZZ'))) tr.addElement(cell) cell = TableCell() cell.addElement(P(text=str(duration))) tr.addElement(cell) cell = TableCell(valuetype="string") cell.addElement(P(text=description)) tr.addElement(cell) cell = TableCell() cell.addElement(P(text=created.format('YYYY-MM-DD HH:mm:ss ZZ'))) tr.addElement(cell) cell = TableCell(valuetype="string") cell.addElement(P(text=location)) tr.addElement(cell) cell = TableCell() link = A(type="simple", href=url, text=url) p = P() p.addElement(link) cell.addElement(p) tr.addElement(cell) textdoc.spreadsheet.addElement(table) textdoc.save(out_file)
# Create a style for the table content. One we can modify # later in the word processor. tablecontents = Style(name="Table Contents", family="paragraph") tablecontents.addElement(ParagraphProperties(numberlines="false", linenumber="0")) tablecontents.addElement(TextProperties(fontweight="bold")) textdoc.styles.addElement(tablecontents) TH = Style(name="THstyle",family="table-cell", parentstylename='Standard', displayname="Table Header") #TH.addElement(TableCellProperties(backgroundcolor="#00FF00")) TH.addElement(ParagraphProperties(textalign="center")) textdoc.styles.addElement(TH) C0 = Style(name="C0style",family="table-cell", parentstylename='Standard', displayname="Color style 0") C0.addElement(TableCellProperties(backgroundcolor="#00FF00")) C0.addElement(ParagraphProperties(textalign="center")) textdoc.styles.addElement(C0) Csep = Style(name="Csepstyle",family="table-cell", parentstylename='Standard', displayname="Color style Sep ") #Csep.addElement(TableCellProperties(backgroundcolor="#FF99FF")) Csep.addElement(ParagraphProperties(textalign="center")) textdoc.styles.addElement(Csep) C1 = Style(name="C1style",family="table-cell", parentstylename='Standard', displayname="Color style 1") #C1.addElement(TableCellProperties(backgroundcolor="#AAFF00")) C1.addElement(TableCellProperties(backgroundcolor="#00FF00")) C1.addElement(ParagraphProperties(textalign="center")) textdoc.styles.addElement(C1) C2 = Style(name="C2style",family="table-cell", parentstylename='Standard', displayname="Color style 2")
def export_odf_report(filename: str, borrowing_facts: Iterable[Tuple[str, str, float]]): # Thanks to https://joinup.ec.europa.eu/svn/odfpy/tags/release-0.9/api-for-odfpy.odt # for example of this API doc = OpenDocumentSpreadsheet() # -------- add styles ----------- vertcell = Style(name="vcell", family="table-cell") vertcell.addElement(TableCellProperties(rotationangle=90)) # -------- create table ---------- # Start the table, and describe the columns table = Table(name="Borrowing") # ------ process some data --------- scols = set(gfn for bfn, gfn, bo in borrowing_facts) cols = sorted(scols) rows = sorted(set(bfn for bfn, gfn, bo in borrowing_facts)) rc: Dict[str, int] = {} rr: Dict[str, int] = {} for c, i in zip(cols, itertools.count()): rc[c] = i for r, i in zip(rows, itertools.count()): rr[r] = i data = [[0.0] * len(cols) for r in rows] # to make different list for bfn, gfn, bo in borrowing_facts: dr = rr[bfn] dc = rc[gfn] data[dr][dc] = bo # --------- go! ---------- tr = TableRow() tc = TableCell() tc.addElement(P(text=r"Borrower \ Source")) tr.addElement(tc) for c in cols: tc = TableCell(stylename=vertcell) tc.addElement(P(text=c)) tr.addElement(tc) table.addElement(tr) for r, rd in zip(rows, data): tr = TableRow() tc = TableCell() tc.addElement(P(text=r)) tr.addElement(tc) for cd in rd: if cd > 0: tc = TableCell(valuetype='percentage', value=cd) else: tc = TableCell() tr.addElement(tc) table.addElement(tr) doc.spreadsheet.addElement(table) doc.save(filename, False)
def fill_bill_table(self): """Fill a table of a bill's items""" #out_dir = u'/smb/system/Scripts/odf_userfields/Contracts/Docs/Bil/2020' doc_name = u"{0}/{1}".format(self.out_dir, self.doc_name) #.decode('utf-8') #print('t={0}, o={1}'.format(templ_filename, doc_name)) doc = load(doc_name) bill_cell_style = Style(name="bill cell style", family="table-cell") #ill_cell_style.addElement(TableCellProperties(border="0.3pt solid #000000")) bill_cell_style.addElement(TableCellProperties()) """ pstyle = Style(name="paragraph style", family="paragraph") pstyle.addElement(ParagraphProperties(textalign="center")) money_style = Style(name="money style", family="paragraph") money_style.addElement(ParagraphProperties(textalign="right")) """ #money_col_style = Style(name="money col style", family="table-column") #money_col_style.addElement(TableColumnProperties(textalign="right")) doc.styles.addElement(bill_cell_style) #doc.styles.addElement(pstyle) #doc.styles.addElement(money_style) #doc.styles.addElement(money_col_style) for elem in doc.getElementsByType(Table): if elem.getAttribute('name') == TABLE_ITEMS: #tab = elem row1 = elem.getElementsByType(TableRow)[1] #row_last = elem.getElementsByType(TableRow)[-1] print('row1=', row1) cells = row1.getElementsByType(TableCell) cell_style = cells[0].getAttribute("stylename") for row_bill in self.bill_items: #print('total=', row_bill["total"]) ord_dict = OrderedDict() ord_dict[1] = row_bill["ПозицияСчета"] ord_dict[2] = row_bill["Наименование"] ord_dict[3] = row_bill["Ед Изм"] ord_dict[4] = row_bill["Кол-во"] ord_dict[5] = row_bill["ЦенаНДС"] ord_dict[6] = row_bill["total"] tr1 = TableRow() for key, val in ord_dict.items( ): # OrderedDict(ROW1).values(): tc1 = TableCell(stylename=cell_style) #tc1 = TableCell() cell_par = cells[key - 1].getElementsByType(P)[0] par_style = cell_par.getAttribute("stylename") tc1.addElement(P(text=str(val), stylename=par_style)) #tc1.setAttribute("stylename", cell_style) tr1.addElement(tc1) #elem.addElement(tr1) elem.insertBefore(tr1, row1) elem.removeChild(row1) #elem.removeChild(row_last) doc.save(doc_name)
for date, times in examinations: for time, possibilities in times: for variable, examinee, examiners in possibilities: if not examinee in examinees and not examinee in undefined: undefined[examinee] = ["without appointment", examiners] ''' for examinee in undefined: print examinee ''' output = OpenDocumentSpreadsheet() middle_center = Style(name="middle_center", family="table-cell") middle_center.addElement(TableCellProperties(verticalalign="middle")) middle_center.addElement(ParagraphProperties(textalign="center")) output.styles.addElement(middle_center) middle_left = Style(name="middle_left", family="table-cell") middle_left.addElement(TableCellProperties(verticalalign="middle")) middle_left.addElement(ParagraphProperties(textalign="left")) output.styles.addElement(middle_left) date_style = Style(name="date", family="table-column") date_style.addElement(TableColumnProperties(columnwidth="5cm")) output.automaticstyles.addElement(date_style) time_style = Style(name="time", family="table-column") time_style.addElement(TableColumnProperties(columnwidth="1.5cm")) output.automaticstyles.addElement(time_style)
def __init__(self): self.textdoc = OpenDocumentText() self.oneandhalflines = Style(name="oneandhalflines", parentstylename="Standard", family="paragraph") self.oneandhalflines.addElement(ParagraphProperties(lineheight="1.5")) self.textdoc.automaticstyles.addElement(self.oneandhalflines) # Create a style for the paragraph with page-break self.withbreak = Style(name="WithBreak", parentstylename="Standard", family="paragraph") self.withbreak.addElement(ParagraphProperties(breakbefore="page")) self.textdoc.automaticstyles.addElement(self.withbreak) self.footercenterstyle = Style(name="footercenter", family="paragraph", parentstylename="Standard") self.footercenterstyle.addElement(ParagraphProperties(textalign="center")) self.textdoc.automaticstyles.addElement(self.footercenterstyle) self.footerstyle = FooterStyle() self.footerstyle.addElement(HeaderFooterProperties(padding="0.05cm",borderleft="none",borderright="none",bordertop="none",borderbottom="none",shadow="none", minheight="1cm")) #Text Header self.plheaderstyle = PageLayout(name="pl") self.plheaderstyle.addElement(PageLayoutProperties(marginleft="2cm",marginright="2cm",margintop="1cm",marginbottom="1cm")) self.headerstyle = HeaderStyle() self.headerstyle.addElement(HeaderFooterProperties(backgroundcolor="#e6e6ff",padding="0.05cm",borderleft="none",borderright="none",bordertop="none",borderbottom="2.01pt solid #000099",shadow="none", minheight="1cm")) self.plheaderstyle.addElement(self.headerstyle) self.plheaderstyle.addElement(self.footerstyle) self.textdoc.automaticstyles.addElement(self.plheaderstyle) #image header self.pliheaderstyle = PageLayout(name="pli") self.pliheaderstyle.addElement(PageLayoutProperties(marginleft="2cm",marginright="2cm",margintop="1cm",marginbottom="1cm")) self.headeristyle = HeaderStyle() self.headeristyle.addElement(HeaderFooterProperties(padding="0.05cm",borderleft="none",borderright="none",bordertop="none",borderbottom="none",shadow="none", minheight="2cm")) self.pliheaderstyle.addElement(self.headeristyle) self.pliheaderstyle.addElement(self.footerstyle) self.textdoc.automaticstyles.addElement(self.pliheaderstyle) self.h1style = Style(name="Heading 1", family="paragraph",parentstylename="Heading 1") self.h1style.addElement(GraphicProperties(fill="solid",fillcolor="#e6e6ff")) self.h1style.addElement(TextProperties(attributes={'fontsize':"14pt",'fontweight':"bold",'color':"#000099" })) self.h1style.addElement(ParagraphProperties(breakbefore="page",margintop="0.4cm",marginbottom="0.2cm",backgroundcolor="#e6e6ff",padding="0.05cm",borderleft="none",borderright="none",bordertop="none",borderbottom="2.01pt solid #000099",shadow="none")) self.textdoc.automaticstyles.addElement(self.h1style) self.h2style = Style(name="Heading 2s", family="paragraph",parentstylename="Heading 2") self.h2style.addElement(TextProperties(attributes={'fontsize':"12pt",'fontweight':"bold",'color':"#000099" })) self.h2style.addElement(ParagraphProperties(marginleft="0cm",marginright="0cm",margintop="0.2cm",marginbottom="0.2cm",lineheight="150%",textindent="1.2cm",autotextindent="false")) self.textdoc.automaticstyles.addElement(self.h2style) self.h2bstyle = Style(name="Heading 2b", family="paragraph",parentstylename="Heading 2") self.h2bstyle.addElement(ParagraphProperties(breakbefore="page",marginleft="0cm",marginright="0cm",margintop="0.2cm",marginbottom="0.2cm",lineheight="150%",textindent="1.2cm",autotextindent="false")) self.textdoc.automaticstyles.addElement(self.h2bstyle) self.h3style = Style(name="Heading 3s", family="paragraph",parentstylename="Heading 3") self.h3style.addElement(TextProperties(attributes={'fontsize':"12pt",'fontweight':"bold",'color':"#000099" })) self.h3style.addElement(ParagraphProperties(marginleft="0cm",marginright="0cm",margintop="0.2cm",marginbottom="0.2cm",lineheight="150%",textindent="1.2cm",autotextindent="false")) self.textdoc.automaticstyles.addElement(self.h3style) self.h3bstyle = Style(name="Heading 3b", family="paragraph",parentstylename="Heading 3") self.h3bstyle.addElement(TextProperties(attributes={'fontsize':"12pt",'fontweight':"bold",'color':"#000099" })) self.h3bstyle.addElement(ParagraphProperties(breakbefore="page",marginleft="0cm",marginright="0cm",margintop="0.2cm",marginbottom="0.2cm",lineheight="150%",textindent="1.2cm",autotextindent="false")) self.textdoc.automaticstyles.addElement(self.h3bstyle) self.TAB_style = Style(name="Table", family="table-cell", parentstylename="Standard") self.TAB_style.addElement(TableCellProperties(border="0.05pt solid #000000")) self.textdoc.automaticstyles.addElement(self.TAB_style) self.TAB_stylered = Style(name="Table red", family="table-cell", parentstylename="Standard") self.TAB_stylered.addElement(TableCellProperties(backgroundcolor="ff0000",border="0.05pt solid #000000")) self.textdoc.automaticstyles.addElement(self.TAB_stylered) self.tableheaders = Style(name="Table Headers", family="paragraph", parentstylename="Standard") self.tableheaders.addElement(ParagraphProperties(numberlines="false", linenumber="0",textalign="center",margintop="0.2cm",marginbottom="0.2cm")) self.tableheaders.addElement(TextProperties(attributes={'fontsize':"12pt",'fontweight':"bold"})) self.textdoc.styles.addElement(self.tableheaders) self.tablecontents = Style(name="Table Contents", family="paragraph", parentstylename="Standard") self.tablecontents.addElement(ParagraphProperties(numberlines="false", linenumber="0",margintop="0.2cm",marginbottom="0.2cm")) self.tablecontents.addElement(TextProperties(attributes={'fontsize':"12pt" })) self.textdoc.styles.addElement(self.tablecontents) self.tablecontentscenter = Style(name="Table Contents Center", family="paragraph", parentstylename="Standard") self.tablecontentscenter.addElement(ParagraphProperties(numberlines="false", linenumber="0", textalign="center",margintop="0.2cm",marginbottom="0.2cm")) self.tablecontentscenter.addElement(TextProperties(attributes={'fontsize':"12pt" })) self.textdoc.styles.addElement(self.tablecontentscenter) self.tablecontentscenterred = Style(name="Table Contents Center Red", family="paragraph", parentstylename="Standard") self.tablecontentscenterred.addElement(ParagraphProperties(numberlines="false", linenumber="0", textalign="center", backgroundcolor="#ff0000",margintop="0.2cm",marginbottom="0.2cm")) self.tablecontentscenterred.addElement(TextProperties(attributes={'fontsize':"12pt" })) self.textdoc.styles.addElement(self.tablecontentscenterred)
def create_doc_with_styles(): textdoc = OpenDocumentSpreadsheet() # Create automatic styles for the column widths. # ODF Standard section 15.9.1 nameColStyle = Style(name="nameColStyle", family="table-column") nameColStyle.addElement(TableColumnProperties(columnwidth="8cm")) textdoc.automaticstyles.addElement(nameColStyle) tagColStyle = Style(name="tagColStyle", family="table-column") tagColStyle.addElement(TableColumnProperties(columnwidth="5cm")) tagColStyle.addElement(ParagraphProperties(textalign="left")) #?? textdoc.automaticstyles.addElement(tagColStyle) rankColStyle = Style(name="rankColStyle", family="table-column") rankColStyle.addElement(TableColumnProperties(columnwidth="1.5cm")) rankColStyle.addElement(ParagraphProperties(textalign="center")) #?? textdoc.automaticstyles.addElement(rankColStyle) valColStyle = Style(name="valColStyle", family="table-column") valColStyle.addElement(TableColumnProperties(columnwidth="0.9cm")) valColStyle.addElement(ParagraphProperties(textalign="center")) #?? textdoc.automaticstyles.addElement(valColStyle) linkColStyle = Style(name="linkColStyle", family="table-column") linkColStyle.addElement(TableColumnProperties(columnwidth="0.3cm")) linkColStyle.addElement(ParagraphProperties(textalign="center")) #?? textdoc.automaticstyles.addElement(linkColStyle) # Create a style for the table content. One we can modify # later in the word processor. tablecontents = Style(name="tablecontents", family="paragraph") tablecontents.addElement( ParagraphProperties(numberlines="false", linenumber="0")) tablecontents.addElement(TextProperties(fontweight="bold")) textdoc.styles.addElement(tablecontents) TH = Style(name="THstyle", family="table-cell", parentstylename='Standard', displayname="Table Header") TH.addElement(ParagraphProperties(textalign="center")) textdoc.styles.addElement(TH) C0 = Style(name="C0style", family="table-cell", parentstylename='Standard', displayname="Color style 0") C0.addElement(TableCellProperties(backgroundcolor="#00FF00")) C0.addElement(ParagraphProperties(textalign="center")) textdoc.styles.addElement(C0) Csep = Style(name="Csepstyle", family="table-cell", parentstylename='Standard', displayname="Color style Sep ") Csep.addElement(ParagraphProperties(textalign="center")) textdoc.styles.addElement(Csep) C1 = Style(name="C1style", family="table-cell", parentstylename='Standard', displayname="Color style 1") C1.addElement(TableCellProperties(backgroundcolor="#00FF00")) C1.addElement(ParagraphProperties(textalign="center")) textdoc.styles.addElement(C1) C2 = Style(name="C2style", family="table-cell", parentstylename='Standard', displayname="Color style 2") C2.addElement(TableCellProperties(backgroundcolor="#FFFF00")) C2.addElement(ParagraphProperties(textalign="center")) textdoc.styles.addElement(C2) C3 = Style(name="C3style", family="table-cell", parentstylename='Standard', displayname="Color style 3") C3.addElement(TableCellProperties(backgroundcolor="#FFAA00")) C3.addElement(ParagraphProperties(textalign="center")) textdoc.styles.addElement(C3) C4 = Style(name="C4style", family="table-cell", parentstylename='Standard', displayname="Color style 4") C4.addElement(TableCellProperties(backgroundcolor="#FF0000")) C4.addElement(ParagraphProperties(textalign="center")) textdoc.styles.addElement(C4) C5 = Style(name="C5style", family="table-cell", parentstylename='Standard', displayname="Color style 5") C5.addElement(TableCellProperties(backgroundcolor="#FF0000")) C5.addElement(ParagraphProperties(textalign="center")) textdoc.styles.addElement(C5) CB = Style(name="CBstyle", family="table-cell", parentstylename='Standard', displayname="Color style blue") CB.addElement(TableCellProperties(backgroundcolor="#8888DD")) CB.addElement(ParagraphProperties(textalign="center")) textdoc.styles.addElement(CB) rankCellStyle = Style(name="rankCellStyle", family="table-cell", parentstylename='Standard', displayname="rankCellStyle") rankCellStyle.addElement(ParagraphProperties(textalign="center")) textdoc.styles.addElement(rankCellStyle) return textdoc
# Create automatic styles for the column widths. widewidth = Style(name="co1", family="table-column") widewidth.addElement( TableColumnProperties(columnwidth="1cm", breakbefore="auto")) textdoc.automaticstyles.addElement(widewidth) cs1 = Style(name="cs1", family="table-cell") cs1.addElement(ParagraphProperties(textalign='center')) cs1.addElement( TextProperties(attributes={ 'fontsize': "10pt", 'fontweight': "bold", 'color': "#CCCCCC" })) cs1.addElement( TableCellProperties(backgroundcolor="#ff0000", border="0.74pt solid #000000")) textdoc.automaticstyles.addElement(cs1) cs2 = Style(name="cs2", family="table-cell") cs2.addElement(ParagraphProperties(textalign='center')) cs2.addElement( TextProperties(attributes={ 'fontsize': "10pt", 'color': "#000000" })) cs2.addElement( TableCellProperties(backgroundcolor="#ffff80", border="0.74pt solid #000000")) textdoc.automaticstyles.addElement(cs2) cs3 = Style(name="cs3", family="table-cell")
Table, ) from odf.text import P from pyexcel_io import service as converter from zope.interface import ( implements, ) from autonomie.interfaces import IExporter TITLE_STYLE = Style(name="title", family="table-cell") TITLE_STYLE.addElement(TextProperties(fontweight="bold", fontsize=16)) HEADER_STYLE = Style(name="header", family="table-cell") HEADER_STYLE.addElement(TextProperties(fontweight="bold")) HEADER_STYLE.addElement(TableCellProperties(backgroundcolor="#D9EDF7")) HIGHLIGHT_STYLE = Style(name="highlight", family="table-cell") HIGHLIGHT_STYLE.addElement(TextProperties(fontweight="bold")) HIGHLIGHT_STYLE.addElement(TableCellProperties(backgroundcolor="#efffef")) logger = logging.getLogger(__name__) class OdsExporter: implements(IExporter) title = u"Export" def __init__(self): self.book = OpenDocumentSpreadsheet() self.book.automaticstyles.addElement(TITLE_STYLE)
def insert_table_(self, ar, column_names=None, table_width=180): # logger.info("20160330 insert_table(%s)", ar) ar.setup_from(self.ar) columns, headers, widths = ar.get_field_info(column_names) widths = map(int, widths) tw = sum(widths) # specifying relative widths doesn't seem to work (and that's # a pity because absolute widths requires us to know the # table_width). use_relative_widths = False if use_relative_widths: width_specs = ["%d*" % (w * 100 / tw) for w in widths] else: width_specs = ["%dmm" % (table_width * w / tw) for w in widths] doc = OpenDocumentText() def add_style(**kw): st = Style(**cleankw(kw)) doc.styles.addElement(st) self.my_styles.append(st) return st table_style_name = str(ar.actor) st = add_style(name=table_style_name, family="table", parentstylename="Default") st.addElement( TableProperties(align="margins", maybreakbetweenrows="0")) # create some *visible* styles st = add_style(name="Table Contents", family="paragraph", parentstylename="Default") st.addElement(ParagraphProperties(numberlines="false", linenumber="0")) st = add_style(name="Number Cell", family="paragraph", parentstylename="Table Contents") st.addElement(ParagraphProperties( numberlines="false", textalign="end", justifysingleword="true", linenumber="0")) dn = "Table Column Header" st = self.stylesManager.styles.getStyle(dn) if st is None: st = add_style(name=dn, family="paragraph", parentstylename="Table Contents") st.addElement( ParagraphProperties(numberlines="false", linenumber="0")) st.addElement(TextProperties(fontweight="bold")) dn = "Bold Text" st = self.stylesManager.styles.getStyle(dn) if st is None: st = add_style(name=dn, family="text", parentstylename="Default") #~ st = add_style(name=dn, family="text") st.addElement(TextProperties(fontweight="bold")) if False: dn = "L1" st = self.stylesManager.styles.getStyle(dn) if st is None: st = ListStyle(name=dn) doc.styles.addElement(st) p = ListLevelProperties( listlevelpositionandspacemode="label-alignment") st.addElement(p) #~ label-followed-by="listtab" text:list-tab-stop-position="1.27cm" fo:text-indent="-0.635cm" fo:margin-left="1.27cm"/> p.addElement(ListLevelLabelAlignment(labelfollowedby="listtab", listtabstopposition="1.27cm", textindent="-0.635cm", marginleft="1.27cm" )) self.my_styles.append(st) #~ list_style = add_style(name=dn, family="list") bullet = text.ListLevelStyleBullet( level=1, stylename="Bullet_20_Symbols", bulletchar=u"•") #~ bullet = text.ListLevelStyleBullet(level=1,stylename="Bullet_20_Symbols",bulletchar=u"*") #~ <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" text:bullet-char="•"> st.addElement(bullet) # create some automatic styles def add_style(**kw): st = Style(**cleankw(kw)) doc.automaticstyles.addElement(st) self.my_automaticstyles.append(st) return st cell_style = add_style(name="Lino Cell Style", family="table-cell") cell_style.addElement(TableCellProperties( paddingleft="1mm", paddingright="1mm", paddingtop="1mm", paddingbottom="0.5mm", border="0.002cm solid #000000")) header_row_style = add_style( name="Lino Header Row", family="table-row", parentstylename=cell_style) header_row_style.addElement( TableRowProperties(backgroundcolor="#eeeeee")) total_row_style = add_style( name="Lino Total Row", family="table-row", parentstylename=cell_style) total_row_style.addElement( TableRowProperties(backgroundcolor="#ffffff")) table = Table(name=table_style_name, stylename=table_style_name) table_columns = TableColumns() table.addElement(table_columns) table_header_rows = TableHeaderRows() table.addElement(table_header_rows) table_rows = TableRows() table.addElement(table_rows) # create table columns and automatic table-column styles for i, fld in enumerate(columns): #~ print 20120415, repr(fld.name) name = str(ar.actor) + "." + str(fld.name) cs = add_style(name=name, family="table-column") if use_relative_widths: cs.addElement( TableColumnProperties(relcolumnwidth=width_specs[i])) else: cs.addElement( TableColumnProperties(columnwidth=width_specs[i])) #~ cs.addElement(TableColumnProperties(useoptimalcolumnwidth='true')) #~ k = cs.getAttribute('name') #~ renderer.stylesManager.styles[k] = toxml(e) #~ doc.automaticstyles.addElement(cs) #~ self.my_automaticstyles.append(cs) table_columns.addElement(TableColumn(stylename=name)) def fldstyle(fld): #~ if isinstance(fld,ext_store.VirtStoreField): #~ fld = fld.delegate if isinstance(fld, NumberFieldElement): return "Number Cell" return "Table Contents" def value2cell(ar, i, fld, val, style_name, tc): # if i == 0: # logger.info("20160330a value2cell(%s, %s)", fld.__class__, val) txt = fld.value2html(ar, val) # if i == 0: # logger.info("20160330b value2cell(%s)", E.tostring(txt)) p = text.P(stylename=style_name) html2odf(txt, p) try: tc.addElement(p) except Exception as e: dd.logger.warning("20120614 addElement %s %s %r : %s", i, fld, val, e) #~ print 20120614, i, fld, val, e #~ yield P(stylename=tablecontents,text=text) # create header row #~ hr = TableRow(stylename=HEADER_ROW_STYLE_NAME) hr = TableRow(stylename=header_row_style) table_header_rows.addElement(hr) for h in headers: #~ for fld in fields: #~ tc = TableCell(stylename=CELL_STYLE_NAME) tc = TableCell(stylename=cell_style) tc.addElement(text.P( stylename="Table Column Header", #~ text=force_text(fld.field.verbose_name or fld.name))) text=force_text(h))) hr.addElement(tc) sums = [fld.zero for fld in columns] for row in ar.data_iterator: #~ for grp in ar.group_headers(row): #~ raise NotImplementedError() tr = TableRow() has_numeric_value = False for i, fld in enumerate(columns): #~ tc = TableCell(stylename=CELL_STYLE_NAME) tc = TableCell(stylename=cell_style) #~ if fld.field is not None: v = fld.field._lino_atomizer.full_value_from_object(row, ar) stylename = fldstyle(fld) if v is None: tc.addElement(text.P(stylename=stylename, text='')) else: value2cell(ar, i, fld, v, stylename, tc) nv = fld.value2num(v) if nv != 0: sums[i] += nv has_numeric_value = True #~ sums[i] += fld.value2num(v) tr.addElement(tc) if has_numeric_value or not ar.actor.hide_zero_rows: table_rows.addElement(tr) if not ar.actor.hide_sums: if sums != [fld.zero for fld in columns]: tr = TableRow(stylename=total_row_style) table_rows.addElement(tr) sums = {fld.name: sums[i] for i, fld in enumerate(columns)} for i, fld in enumerate(columns): tc = TableCell(stylename=cell_style) stylename = fldstyle(fld) p = text.P(stylename=stylename) e = fld.format_sum(ar, sums, i) html2odf(e, p) tc.addElement(p) #~ if len(txt) != 0: #~ msg = "html2odf() returned " #~ logger.warning(msg) #~ txt = tuple(html2odf(fld.format_sum(ar,sums,i),p)) #~ assert len(txt) == 1 #~ tc.addElement(text.P(stylename=stylename,text=txt[0])) tr.addElement(tc) doc.text.addElement(table) return toxml(table)
def recolor(fileName, markingFileName, outputFileName): # Load the document logger.info("Load %s" % fileName) doc = load(fileName) # Create the styles style = Style(name="TabLinker", family="table-cell", parentstylename="Default") doc.styles.addElement(style) for (style_name, style_color) in tl_styles.iteritems(): style = Style(name=style_name, family="table-cell", parentstylename="TabLinker") style.addElement(TableCellProperties(backgroundcolor=style_color)) doc.styles.addElement(style) # Import color marking if it exists if os.path.exists(markingFileName): logger.info('Load {0}'.format(markingFileName)) marking = {} for mrk in open(markingFileName): (index_str, cell, style) = mrk.strip().split(';') index = int(index_str) marking.setdefault(index, {}) marking[index][cell] = style logger.info('Apply colors') # Make a cache of the automatic styles autoStylesCache = {} # Replacement styles for those use for different markings autoStylesCache['mapping'] = {} # The styles autoStylesCache['styles'] = {} # Last index of automated style name autoStylesCache['lastIndex'] = 0 # The root in the document autoStylesCache['root'] = doc.getElementsByType(Style)[0].parentNode for st in doc.getElementsByType(Style): styleName = st.getAttrNS(STYLENS, 'name') autoStylesCache['styles'][styleName] = st autoStylesCache['mapping'][styleName] = {} if styleName.startswith('ce'): index = int(styleName.replace('ce', '')) if index > autoStylesCache['lastIndex']: autoStylesCache['lastIndex'] = index # Start coloring tables = doc.getElementsByType(Table) for tableIndex in range(0, len(tables)): if tableIndex in marking: coloredCells = set() table = tables[tableIndex] rows = table.getElementsByType(TableRow) for rowIndex in range(0, len(rows)): cols = getColumns(rows[rowIndex]) for colIndex in range(0, len(cols)): cell = cols[colIndex] # Ignore cells that are spanned over if cell == None or cell in coloredCells: continue # Get the cell name and the current style cellName = colName(colIndex) + str(rowIndex + 1) # Debug #if cellName in ['A1', 'B3', 'G3','J8']: # logger.setLevel(logging.DEBUG) #else: # logger.setLevel(logging.INFO) # Get the color to assign to the cell, if any if cellName not in marking[tableIndex]: color = 'Default' # use default as parent style else: color = marking[tableIndex][cellName] # Change the color logger.debug("--- %s ---" % cellName) setColor(cell, autoStylesCache, color) # Add the cell to the set of colored ones # (rows can contain copies of cells if they span) coloredCells.add(cell) # Suppress the background colors # Suppress the other color if any for (cellStyleName, cellStyle) in autoStylesCache['styles'].iteritems(): if cellStyleName.startswith('ce'): for current in cellStyle.getElementsByType( TableCellProperties): currentVal = current.getAttrNS(FONS, 'background-color') if current != None and currentVal != None: current.removeAttrNS(FONS, 'background-color') # Save logger.info('Save {0}'.format(outputFileName)) doc.save(outputFileName)