def createFinalReportTargetFormat(self, finalReport: List[list]) -> bytes: textdoc = OpenDocumentSpreadsheet() tablecontents = Style(name="Table Contents", family="paragraph") tablecontents.addElement( ParagraphProperties(numberlines="false", linenumber="0")) tablecontents.addElement(TextProperties(fontweight="bold")) textdoc.styles.addElement(tablecontents) table = Table(name="Java Metrics") tr = self.newRow(table) for columnLabels in finalReport[0]: self.addElementToRow(columnLabels, "string", tr, tablecontents) for row in finalReport[1:]: tr = self.newRow(table) self.addElementToRow(row[0], "string", tr, tablecontents) self.addElementToRow(row[1], "string", tr, tablecontents) for element in row[2:]: self.addElementToRow(str(element), "float", tr, tablecontents) textdoc.spreadsheet.addElement(table) stringOutput = BytesIO() textdoc.write(stringOutput) return stringOutput.getvalue()
def export_ods (headers, data): doc = OpenDocumentSpreadsheet() style = Style(name="Large number", family="table-cell") style.addElement(TextProperties(fontfamily="Arial", fontsize="15pt")) doc.styles.addElement(style) widewidth = Style(name="co1", family="table-column") widewidth.addElement(TableColumnProperties(columnwidth="2.8cm", breakbefore="auto")) doc.automaticstyles.addElement(widewidth) table = Table() if len (headers) > 0: tr = TableRow () table.addElement (tr) for item in headers: tc = TableCell () tr.addElement (tc) p = P(stylename = style, text = txt(item)) tc.addElement (p) for line in data: tr = TableRow () table.addElement (tr) for item in line: tc = TableCell () tr.addElement (tc) p = P (stylename = style, text = txt(item)) tc.addElement (p) doc.spreadsheet.addElement(table) buffer = StringIO () doc.write(buffer) return buffer.getvalue ()
def get_odf_spreadsheet(sheets): """Creates a spreadsheet from a dictionary sheets of dictionary entries sheetname -> nested list of rows""" doc = OpenDocumentSpreadsheet() spreadsheet = doc.spreadsheet for sheet_name, list_rows in sheets.iteritems(): sheet = Table() spreadsheet.addElement(sheet) sheet.setAttribute("name", sheet_name) for list_row in list_rows: table_row = TableRow() for cell_content in list_row: vtype = valuetype(cell_content) if vtype == "boolean": cell_content = ("True" if cell_content else "False") vtype = "string" elif vtype == "string": cell_content = unicodedata.normalize( 'NFKD', unicode(cell_content)).encode('ascii', 'ignore') table_cell = TableCell(valuetype=vtype, value=cell_content) if vtype == "string": s = str(cell_content) table_cell.addElement(P(text=s)) table_row.addElement(table_cell) sheet.addElement(table_row) st = StringIO() doc.write(st) return st.getvalue()
def createTargetFormat(self, metricValues: Dict[str, List[int]], metricLabels: List[str]) -> bytes: textdoc = OpenDocumentSpreadsheet() tablecontents = Style(name="Table Contents", family="paragraph") tablecontents.addElement( ParagraphProperties(numberlines="false", linenumber="0")) tablecontents.addElement(TextProperties(fontweight="bold")) textdoc.styles.addElement(tablecontents) table = Table(name="Java Metrics") tr = self.newRow(table) for metricLabel in metricLabels: self.addElementToRow(metricLabel, "string", tr, tablecontents) for methodName in metricValues.keys(): tr = self.newRow(table) self.addElementToRow(methodName, "string", tr, tablecontents) for metricValue in metricValues[methodName]: self.addElementToRow(str(metricValue), "float", tr, tablecontents) textdoc.spreadsheet.addElement(table) stringOutput = BytesIO() textdoc.write(stringOutput) return stringOutput.getvalue()
def writer(data, **kwargs): """ Liberally adapted from odfpy's csv2ods script. """ def handle_formula(f): return TableCell(valuetype="float", formula="{}".format(f)) textdoc = OpenDocumentSpreadsheet(**kwargs) # 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) # Start the table table = Table(name=u'Sheet 1') fltExp = re.compile('^\s*[-+]?\d+(\.\d+)?\s*$') for row in data: tr = TableRow() table.addElement(tr) for val in row: if isinstance(val, spreadsheet.Formula): tc = handle_formula(val) else: valuetype = 'string' if not isinstance(val, unicode): if isinstance(val, str): text_value = "{}".format(val, PWENC, 'replace') else: text_value = "{}".format(val) else: text_value = val if isinstance(val, (float, int, long)) or (isinstance( val, str) and fltExp.match(text_value)): valuetype = 'float' if valuetype == 'float': tc = TableCell(valuetype="float", value=text_value.strip()) else: tc = TableCell(valuetype=valuetype) if val is not None: p = P(stylename=tablecontents, text=text_value) tc.addElement(p) tr.addElement(tc) textdoc.spreadsheet.addElement(table) result = StringIO() textdoc.write(result) return result.getvalue()
def __call__(self, spreadsheet, file): """ Writes all data from spreadsheet into file. """ doc = OpenDocumentSpreadsheet() for sheet in spreadsheet: table = Table(name=sheet.name) self.write_sheet(sheet, table) doc.spreadsheet.addElement(table) doc.write(file)
class ODSWriter(BookWriter): """ open document spreadsheet writer """ def __init__(self, file, **keywords): BookWriter.__init__(self, file, **keywords) self.native_book = OpenDocumentSpreadsheet() def create_sheet(self, name): """ write a row into the file """ return ODSSheetWriter(self.native_book, None, name) def close(self): """ This call writes file """ self.native_book.write(self.file)
class ODSWriter(BookWriter): """ open document spreadsheet writer """ def __init__(self): BookWriter.__init__(self) self.native_book = OpenDocumentSpreadsheet() def create_sheet(self, name): """ write a row into the file """ return ODSSheetWriter(self.native_book, None, name) def close(self): """ This call writes file """ self.native_book.write(self.file_alike_object)
class ODSWriter(IWriter): """ open document spreadsheet writer """ def __init__(self, file_alike_object, file_type, **_): self.file_alike_object = file_alike_object self._native_book = OpenDocumentSpreadsheet() def create_sheet(self, name): """ write a row into the file """ return ODSSheetWriter(self._native_book, name) def close(self): """ This call writes file """ self._native_book.write(self.file_alike_object) self._native_book = None
def to_ods(self, *selection): if not ODFLIB_INSTALLED: raise ODFLIBNotInstalled(_('odfpy not installed.')) if self.fcn_list: stat_list = self.fcn_list[:] order_text = " Ordered by: " + self.sort_type + '\n' else: stat_list = self.stats.keys() order_text = " Random listing order was used\n" for s in selection: stat_list, __ = self.eval_print_amount(s, stat_list, '') spreadsheet = OpenDocumentSpreadsheet() table = Table(name="Profile") for fn in self.files: tcf = TableCell() tcf.addElement(P(text=fn)) trf = TableRow() trf.addElement(tcf) table.addElement(trf) tc_summary = TableCell() summary_text = '%d function calls (%d primitive calls) in %.6f \ seconds' % (self.total_calls, self.prim_calls, self.total_tt) tc_summary.addElement(P(text=summary_text)) tr_summary = TableRow() tr_summary.addElement(tc_summary) table.addElement(tr_summary) tc_order = TableCell() tc_order.addElement(P(text=order_text)) tr_order = TableRow() tr_order.addElement(tc_order) table.addElement(tr_order) tr_header = TableRow() tc_cc = TableCell() tc_cc.addElement(P(text='Total Call Count')) tr_header.addElement(tc_cc) tc_pc = TableCell() tc_pc.addElement(P(text='Primitive Call Count')) tr_header.addElement(tc_pc) tc_tt = TableCell() tc_tt.addElement(P(text='Total Time(seconds)')) tr_header.addElement(tc_tt) tc_pc = TableCell() tc_pc.addElement(P(text='Time Per call(seconds)')) tr_header.addElement(tc_pc) tc_ct = TableCell() tc_ct.addElement(P(text='Cumulative Time(seconds)')) tr_header.addElement(tc_ct) tc_pt = TableCell() tc_pt.addElement(P(text='Cumulative Time per call(seconds)')) tr_header.addElement(tc_pt) tc_nfl = TableCell() tc_nfl.addElement(P(text='filename:lineno(function)')) tr_header.addElement(tc_nfl) table.addElement(tr_header) for func in stat_list: cc, nc, tt, ct, __ = self.stats[func] tr_header = TableRow() tc_nc = TableCell() tc_nc.addElement(P(text=nc)) tr_header.addElement(tc_nc) tc_pc = TableCell() tc_pc.addElement(P(text=cc)) tr_header.addElement(tc_pc) tc_tt = TableCell() tc_tt.addElement(P(text=tt)) tr_header.addElement(tc_tt) tc_tpc = TableCell() tc_tpc.addElement(P(text=(None if nc == 0 else float(tt) / nc))) tr_header.addElement(tc_tpc) tc_ct = TableCell() tc_ct.addElement(P(text=ct)) tr_header.addElement(tc_ct) tc_tpt = TableCell() tc_tpt.addElement(P(text=(None if cc == 0 else float(ct) / cc))) tr_header.addElement(tc_tpt) tc_nfl = TableCell() tc_nfl.addElement(P(text=func)) tr_header.addElement(tc_nfl) table.addElement(tr_header) spreadsheet.spreadsheet.addElement(table) tmp_ods = tempfile.TemporaryFile() spreadsheet.write(tmp_ods) tmp_ods.seek(0) data = tmp_ods.read() os.close(tmp_ods) return data
def to_ods(self, *selection): if not ODFLIB_INSTALLED: raise ODFLIBNotInstalled(_("odfpy not installed.")) if self.fcn_list: stat_list = self.fcn_list[:] order_text = " Ordered by: " + self.sort_type + "\n" else: stat_list = self.stats.keys() order_text = " Random listing order was used\n" for s in selection: stat_list, __ = self.eval_print_amount(s, stat_list, "") spreadsheet = OpenDocumentSpreadsheet() table = Table(name="Profile") for fn in self.files: tcf = TableCell() tcf.addElement(P(text=fn)) trf = TableRow() trf.addElement(tcf) table.addElement(trf) tc_summary = TableCell() summary_text = ( "%d function calls (%d primitive calls) in %.6f \ seconds" % (self.total_calls, self.prim_calls, self.total_tt) ) tc_summary.addElement(P(text=summary_text)) tr_summary = TableRow() tr_summary.addElement(tc_summary) table.addElement(tr_summary) tc_order = TableCell() tc_order.addElement(P(text=order_text)) tr_order = TableRow() tr_order.addElement(tc_order) table.addElement(tr_order) tr_header = TableRow() tc_cc = TableCell() tc_cc.addElement(P(text="Total Call Count")) tr_header.addElement(tc_cc) tc_pc = TableCell() tc_pc.addElement(P(text="Primitive Call Count")) tr_header.addElement(tc_pc) tc_tt = TableCell() tc_tt.addElement(P(text="Total Time(seconds)")) tr_header.addElement(tc_tt) tc_pc = TableCell() tc_pc.addElement(P(text="Time Per call(seconds)")) tr_header.addElement(tc_pc) tc_ct = TableCell() tc_ct.addElement(P(text="Cumulative Time(seconds)")) tr_header.addElement(tc_ct) tc_pt = TableCell() tc_pt.addElement(P(text="Cumulative Time per call(seconds)")) tr_header.addElement(tc_pt) tc_nfl = TableCell() tc_nfl.addElement(P(text="filename:lineno(function)")) tr_header.addElement(tc_nfl) table.addElement(tr_header) for func in stat_list: cc, nc, tt, ct, __ = self.stats[func] tr_header = TableRow() tc_nc = TableCell() tc_nc.addElement(P(text=nc)) tr_header.addElement(tc_nc) tc_pc = TableCell() tc_pc.addElement(P(text=cc)) tr_header.addElement(tc_pc) tc_tt = TableCell() tc_tt.addElement(P(text=tt)) tr_header.addElement(tc_tt) tc_tpc = TableCell() tc_tpc.addElement(P(text=(None if nc == 0 else float(tt) / nc))) tr_header.addElement(tc_tpc) tc_ct = TableCell() tc_ct.addElement(P(text=ct)) tr_header.addElement(tc_ct) tc_tpt = TableCell() tc_tpt.addElement(P(text=(None if cc == 0 else float(ct) / cc))) tr_header.addElement(tc_tpt) tc_nfl = TableCell() tc_nfl.addElement(P(text=func)) tr_header.addElement(tc_nfl) table.addElement(tr_header) spreadsheet.spreadsheet.addElement(table) tmp_ods = tempfile.TemporaryFile() spreadsheet.write(tmp_ods) tmp_ods.seek(0) data = tmp_ods.read() os.close(tmp_ods) return data
class Document: """An OpenDocumentSpreadsheet under construction""" mimetype = 'application/vnd.oasis.opendocument.spreadsheet' def __init__(self, filename=None): self.doc = OpenDocumentSpreadsheet() self.filename = filename # Add some common styles self.tablecontents = Style(name="Table Contents", family="paragraph") self.tablecontents.addElement( ParagraphProperties(numberlines="false", linenumber="0")) self.doc.styles.addElement(self.tablecontents) self.currencystyle = self._add_currencystyle() self.boldcurrencystyle = Style(name="BoldPounds", family="table-cell", parentstylename=self.currencystyle) self.boldcurrencystyle.addElement(TextProperties(fontweight="bold")) self.doc.styles.addElement(self.boldcurrencystyle) self.boldtextstyle = Style(name="BoldText", family="table-cell", parentstylename=self.tablecontents) self.boldtextstyle.addElement(TextProperties(fontweight="bold")) self.doc.styles.addElement(self.boldtextstyle) self._widthstyles = {} def intcell(self, val): return TableCell(valuetype="float", value=val) numbercell = intcell def textcell(self, text): tc = TableCell(valuetype="string") tc.addElement(P(text=text)) return tc @property def datestyle(self): if not hasattr(self, "_datestyle"): self._datestyle = self._add_datestyle() return self._datestyle @property def datetimestyle(self): if not hasattr(self, "_datetimestyle"): self._datetimestyle = self._add_datestyle(name="DateTime", include_time=True) return self._datetimestyle def _add_datestyle(self, name="Date", include_time=False): """Construct a date style""" slash = number.Text() slash.addText('/') ds = number.DateStyle(name="Date", automaticorder="true", formatsource="language") ds.addElement(number.Day()) ds.addElement(slash) ds.addElement(number.Month()) ds.addElement(slash) ds.addElement(number.Year()) if include_time: space = number.Text() space.addText(' ') colon = number.Text() colon.addText(':') ds.addElement(space) ds.addElement(number.Hours()) ds.addElement(colon) ds.addElement(number.Minutes()) self.doc.styles.addElement(ds) datestyle = Style(name=name, family="table-cell", parentstylename="Default", datastylename=name) self.doc.styles.addElement(datestyle) return datestyle def datecell(self, date, style=None): if not style: style = self.datestyle return TableCell(valuetype="date", datevalue=date.isoformat(), stylename=style) def datetimecell(self, datetime, style=None): if not style: style = self.datetimestyle return TableCell(valuetype="date", datevalue=datetime.isoformat(), stylename=style) def _add_currencystyle(self, name="Pounds"): """Construct a currency style""" cs = number.CurrencyStyle(name=name) symbol = number.CurrencySymbol(language="en", country="GB") symbol.addText("£") cs.addElement(symbol) n = number.Number(decimalplaces=2, minintegerdigits=1, grouping="true") cs.addElement(n) self.doc.styles.addElement(cs) currencystyle = Style(name=name, family="table-cell", parentstylename="Default", datastylename=name) self.doc.styles.addElement(currencystyle) return currencystyle def moneycell(self, m, formula=None, style=None): a = { "valuetype": "currency", "currency": "GBP", "stylename": style if style else self.currencystyle, } if m is not None: a["value"] = str(m) if formula is not None: a["formula"] = formula return TableCell(**a) @property def headerstyle(self): if not hasattr(self, "_headerstyle"): self._headerstyle = self._add_headerstyle() return self._headerstyle def _add_headerstyle(self): header = Style(name="ColumnHeader", family="table-cell") header.addElement(ParagraphProperties(textalign="center")) header.addElement(TextProperties(fontweight="bold")) self.doc.styles.addElement(header) return header def headercell(self, text, style=None): if not style: style = self.headerstyle tc = TableCell(valuetype="string", stylename=style) tc.addElement(P(stylename=style, text=text)) return tc def colwidth(self, width): if width not in self._widthstyles: w = Style(name="W{}".format(width), family="table-column") w.addElement(TableColumnProperties(columnwidth=width)) self.doc.automaticstyles.addElement(w) self._widthstyles[width] = w return self._widthstyles[width] def add_table(self, table): self.doc.spreadsheet.addElement(table.as_table()) def as_response(self): r = HttpResponse(content_type=self.mimetype) if self.filename: r['Content-Disposition'] = 'attachment; filename={}'.format( self.filename) self.doc.write(r) return r
class Document: """An OpenDocumentSpreadsheet under construction""" mimetype = 'application/vnd.oasis.opendocument.spreadsheet' def __init__(self, filename=None): self.doc = OpenDocumentSpreadsheet() self.filename = filename # Add some common styles self.tablecontents = Style(name="Table Contents", family="paragraph") self.tablecontents.addElement( ParagraphProperties(numberlines="false", linenumber="0")) self.doc.styles.addElement(self.tablecontents) self.currencystyle = self._add_currencystyle() self.boldcurrencystyle = Style(name="BoldPounds", family="table-cell", parentstylename=self.currencystyle) self.boldcurrencystyle.addElement( TextProperties(fontweight="bold")) self.doc.styles.addElement(self.boldcurrencystyle) self.boldtextstyle = Style(name="BoldText", family="table-cell", parentstylename=self.tablecontents) self.boldtextstyle.addElement(TextProperties(fontweight="bold")) self.doc.styles.addElement(self.boldtextstyle) self._widthstyles = {} def intcell(self, val): return TableCell(valuetype="float", value=val) numbercell = intcell def textcell(self, text): tc = TableCell(valuetype="string") tc.addElement(P(text=text)) return tc @property def datestyle(self): if not hasattr(self, "_datestyle"): self._datestyle = self._add_datestyle() return self._datestyle @property def datetimestyle(self): if not hasattr(self, "_datetimestyle"): self._datetimestyle = self._add_datestyle( name="DateTime", include_time=True) return self._datetimestyle def _add_datestyle(self, name="Date", include_time=False): """Construct a date style""" slash = number.Text() slash.addText('/') ds = number.DateStyle(name="Date", automaticorder="true", formatsource="language") ds.addElement(number.Day()) ds.addElement(slash) ds.addElement(number.Month()) ds.addElement(slash) ds.addElement(number.Year()) if include_time: space = number.Text() space.addText(' ') colon = number.Text() colon.addText(':') ds.addElement(space) ds.addElement(number.Hours()) ds.addElement(colon) ds.addElement(number.Minutes()) self.doc.styles.addElement(ds) datestyle = Style(name=name, family="table-cell", parentstylename="Default", datastylename=name) self.doc.styles.addElement(datestyle) return datestyle def datecell(self, date, style=None): if not style: style = self.datestyle return TableCell( valuetype="date", datevalue=date.isoformat(), stylename=style) def datetimecell(self, datetime, style=None): if not style: style = self.datetimestyle return TableCell( valuetype="date", datevalue=datetime.isoformat(), stylename=style) def _add_currencystyle(self, name="Pounds"): """Construct a currency style""" cs = number.CurrencyStyle(name=name) symbol = number.CurrencySymbol(language="en", country="GB") symbol.addText("£") cs.addElement(symbol) n = number.Number(decimalplaces=2, minintegerdigits=1, grouping="true") cs.addElement(n) self.doc.styles.addElement(cs) currencystyle = Style(name=name, family="table-cell", parentstylename="Default", datastylename=name) self.doc.styles.addElement(currencystyle) return currencystyle def moneycell(self, m, formula=None, style=None): a = { "valuetype": "currency", "currency": "GBP", "stylename": style if style else self.currencystyle, } if m is not None: a["value"] = str(m) if formula is not None: a["formula"] = formula return TableCell(**a) @property def headerstyle(self): if not hasattr(self, "_headerstyle"): self._headerstyle = self._add_headerstyle() return self._headerstyle def _add_headerstyle(self): header = Style(name="ColumnHeader", family="table-cell") header.addElement( ParagraphProperties(textalign="center")) header.addElement( TextProperties(fontweight="bold")) self.doc.styles.addElement(header) return header def headercell(self, text, style=None): if not style: style = self.headerstyle tc = TableCell(valuetype="string", stylename=style) tc.addElement(P(stylename=style, text=text)) return tc def colwidth(self, width): if width not in self._widthstyles: w = Style(name="W{}".format(width), family="table-column") w.addElement(TableColumnProperties(columnwidth=width)) self.doc.automaticstyles.addElement(w) self._widthstyles[width] = w return self._widthstyles[width] def add_table(self, table): self.doc.spreadsheet.addElement(table.as_table()) def as_response(self): r = HttpResponse(content_type=self.mimetype) if self.filename: r['Content-Disposition'] = 'attachment; filename={}'.format( self.filename) self.doc.write(r) return r
def par_classe(classes, fileout): ods = OpenDocumentSpreadsheet() style_civilite = Style(parent=ods.automaticstyles, name='col_civilite', family='table-column') TableColumnProperties(parent=style_civilite, columnwidth='1cm') style_nom = Style(parent=ods.automaticstyles, name='col_nom', family='table-column') TableColumnProperties(parent=style_nom, columnwidth='4.5cm') style_date = Style(parent=ods.automaticstyles, name='col_date', family='table-column') TableColumnProperties(parent=style_date, columnwidth='3.2cm') style_internat = Style(parent=ods.automaticstyles, name='col_internat', family='table-column') TableColumnProperties(parent=style_internat, columnwidth='3.2cm') style_classe = Style(parent=ods.automaticstyles, name='col_classe', family='table-column') TableColumnProperties(parent=style_classe, columnwidth='3.2cm') style_etat_voeu = Style(parent=ods.automaticstyles, name='col_etat_voeu', family='table-column') TableColumnProperties(parent=style_etat_voeu, columnwidth='4cm') style_titre = Style(parent=ods.automaticstyles, name='cell_titre', family='table-cell') TextProperties(parent=style_titre, fontweight='bold', fontsize='14pt') ParagraphProperties(parent=style_titre, textalign='center') style_ligne_titre = Style(parent=ods.automaticstyles, name='ligne_titre', family='table-row') TableRowProperties(parent=style_ligne_titre, rowheight='8mm') style_entete = Style(parent=ods.automaticstyles, name='cell_entete', family='table-cell') TextProperties(parent=style_entete, fontweight='bold') number_style_date_format = odf.number.DateStyle(parent=ods.automaticstyles, name='date_number') odf.number.Day(parent=number_style_date_format, style='long') odf.number.Text(parent=number_style_date_format, text="/") odf.number.Month(parent=number_style_date_format, style='long') odf.number.Text(parent=number_style_date_format, text="/") odf.number.Year(parent=number_style_date_format, style='long') style_date_format = Style(parent=ods.automaticstyles, name='cell_date', family='table-cell', datastylename=number_style_date_format) for classe in classes: table = Table(name=str(classe)) table.addElement(TableColumn(stylename=style_civilite)) # Sexe table.addElement(TableColumn(stylename=style_nom)) # Nom table.addElement(TableColumn(stylename=style_nom)) # Prénom table.addElement( TableColumn(stylename=style_date)) # Date de naissance table.addElement(TableColumn(stylename=style_internat)) # Internat table.addElement(TableColumn(stylename=style_etat_voeu)) # État vœu table.addElement(TableColumn(stylename=style_nom)) # E-mail table.addElement(TableColumn(stylename=style_nom)) # Téléphone table.addElement(TableColumn(stylename=style_nom)) # Mobile # En-tête de la feuille tr = TableRow(parent=table, stylename=style_ligne_titre) cell = TableCell(parent=tr, numbercolumnsspanned=9, numberrowsspanned=1, valuetype='string', stylename=style_titre) cell.addElement(P(text=str(classe))) CoveredTableCell(parent=tr, numbercolumnsrepeated=8) tr = TableRow(parent=table) TableCell(parent=tr) # Sexe P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Nom") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Prénom") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Date de naissance") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Internat") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="État Parcoursup") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="E-mail") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Téléphone") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Mobile") for etudiant in classe.admissions().order_by('nom'): tr = TableRow() table.addElement(tr) TableCell(parent=tr, valuetype='string').addElement( P(text=etudiant.get_sexe_display())) TableCell(parent=tr, valuetype='string').addElement(P(text=etudiant.nom)) TableCell(parent=tr, valuetype='string').addElement(P(text=etudiant.prenom)) cell = TableCell(valuetype='date', datevalue=str(etudiant.date_naissance), stylename=style_date_format) cell.addElement(P(text=etudiant.date_naissance)) tr.addElement(cell) cell = TableCell(valuetype='string') if etudiant.proposition_actuelle.internat: cell.addElement(P(text="Interne")) tr.addElement(cell) TableCell(parent=tr, valuetype='string').addElement( P(text=etudiant.proposition_actuelle.get_etat_display())) TableCell(parent=tr, valuetype='string').addElement(P(text=etudiant.email)) TableCell(parent=tr, valuetype='string').addElement( P(text=etudiant.telephone)) TableCell(parent=tr, valuetype='string').addElement( P(text=etudiant.telephone_mobile)) ods.spreadsheet.addElement(table) # Liste générale pour l'infirmerie table = Table(name="Infirmerie") ods.spreadsheet.addElement(table) table.addElement(TableColumn(stylename=style_civilite)) # Sexe table.addElement(TableColumn(stylename=style_nom)) # Nom table.addElement(TableColumn(stylename=style_nom)) # Prénom table.addElement(TableColumn(stylename=style_classe)) # Classe table.addElement(TableColumn(stylename=style_date)) # Date de naissance table.addElement(TableColumn(stylename=style_internat)) # Internat # En-tête de la feuille tr = TableRow(parent=table, stylename=style_ligne_titre) cell = TableCell(parent=tr, numbercolumnsspanned=9, numberrowsspanned=1, valuetype='string', stylename=style_titre) cell.addElement(P(text="Liste de tous les étudiants admis")) tr = TableRow(parent=table) TableCell(parent=tr) # Sexe P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Nom") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Prénom") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Classe") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Date de naissance") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Internat") for etudiant in Etudiant.objects.filter( proposition_actuelle__isnull=False, proposition_actuelle__date_demission__isnull=True).order_by( 'nom', 'prenom'): tr = TableRow(parent=table) TableCell(parent=tr, valuetype='string').addElement( P(text=etudiant.get_sexe_display())) TableCell(parent=tr, valuetype='string').addElement(P(text=etudiant.nom)) TableCell(parent=tr, valuetype='string').addElement(P(text=etudiant.prenom)) TableCell(parent=tr, valuetype='string').addElement( P(text=str(etudiant.proposition_actuelle.classe))) cell = TableCell(valuetype='date', datevalue=str(etudiant.date_naissance), stylename=style_date_format) cell.addElement(P(text=etudiant.date_naissance)) tr.addElement(cell) cell = TableCell(valuetype='string') if etudiant.proposition_actuelle.internat: cell.addElement(P(text="Interne")) tr.addElement(cell) ods.write(fileout)
class OdsExporter: implements(IExporter) title = u"Export" def __init__(self): self.book = OpenDocumentSpreadsheet() self.book.automaticstyles.addElement(TITLE_STYLE) self.book.automaticstyles.addElement(HEADER_STYLE) self.book.automaticstyles.addElement(HIGHLIGHT_STYLE) self.sheet = Table(name=self.title) self.book.spreadsheet.addElement(self.sheet) def add_title(self, title, width): row = TableRow() cell = TableCell(stylename="title") cell.setAttrNS(TABLENS, "number-columns-spanned", width) cell.addElement(P(text=title)) row.addElement(cell) self.sheet.addElement(row) def add_breakline(self): self._add_row(['\n']) def _get_cell(self, label, stylename=None): """ Build a TableCell and adapt the format to the provided label format :param label: The data to write (int/float/bool/date/str/unicode) :param str stylename: One of the stylenames added in the __init__ :returns: A TableCell instance """ if stylename is not None: cell_to_be_written = TableCell(stylename=stylename) else: cell_to_be_written = TableCell() cell_type = type(label) cell_odf_type = converter.ODS_WRITE_FORMAT_COVERSION.get( cell_type, "string" ) cell_to_be_written.setAttrNS(OFFICENS, "value-type", cell_odf_type) cell_odf_value_token = converter.VALUE_TOKEN.get( cell_odf_type, "value", ) converter_func = converter.ODS_VALUE_CONVERTERS.get( cell_odf_type, None ) if converter_func: label = converter_func(label) if cell_odf_type != 'string': cell_to_be_written.setAttrNS(OFFICENS, cell_odf_value_token, label) cell_to_be_written.addElement(P(text=label)) else: lines = label.split('\n') for line in lines: cell_to_be_written.addElement(P(text=line)) return cell_to_be_written def _add_row(self, labels, cell_style_name=None): row = TableRow() for label in labels: cell = self._get_cell(label, cell_style_name) row.addElement(cell) self.sheet.addElement(row) def add_headers(self, datas): self._add_row(datas, "header") def add_row(self, datas): self._add_row(datas) def add_highlighted_row(self, datas): self._add_row(datas, "highlight") def render(self, f_buf=None): if f_buf is None: f_buf = cStringIO.StringIO() self.book.write(f_buf) return f_buf
def classe_resultats_odf(request, resultats): response = HttpResponse( content_type='application/vnd.oasis.opendocument.spreadsheet') response[ 'Content-Disposition'] = 'attachment; filename="resultats_{}.ods"'.format( resultats['classe']) ods = OpenDocumentSpreadsheet() # Style numérique pour les notes style_number_note = NumberStyle(name="Note") ods.styles.addElement(style_number_note) Number(parent=style_number_note, minintegerdigits=1, decimalplaces=2) style_note = Style(datastylename=style_number_note, parent=ods.styles, name="Note", family='table-cell') # Style pour le rang style_number_rang = NumberStyle(name="Rang", parent=ods.styles) Number(parent=style_number_rang, minintegerdigits=1, decimalplaces=0) style_rang = Style(datastylename=style_number_rang, parent=ods.styles, name="Rang", family='table-column') for matiere, ens_resultats in resultats['enseignements'].items(): table = Table(name="{} - {}".format(resultats['classe'], matiere), parent=ods.spreadsheet) # Création des colonnes table.addElement(TableColumn()) # Étudiant table.addElement(TableColumn()) # Moyenne table.addElement(TableColumn(stylename=style_rang)) # Rang for _ in range(len(resultats['semaines'])): table.addElement(TableColumn()) # Ligne d'en-tête th = TableHeaderRows(parent=table) tr = TableRow(parent=th) P(parent=TableCell(parent=tr, valuetype='string'), text="Étudiant") P(parent=TableCell(parent=tr, valuetype='string'), text="Moyenne") P(parent=TableCell(parent=tr, valuetype='string'), text="Rang") for semaine in resultats['semaines']: P(parent=TableCell(parent=tr, valuetype='string'), text=semaine.numero) # Ligne pour chaque étudiant for etudiant, etu_resultats in ens_resultats['etudiants'].items(): tr = TableRow(parent=table) # Nom de l'étudiant P(parent=TableCell(parent=tr, valuetype='string'), text=str(etudiant)) # Moyenne de l'étudiant P(parent=TableCell(parent=tr, valuetype='float', value=etu_resultats['moyenne'], stylename=style_note), text="{:.2f}".format(etu_resultats['moyenne'])) # Rang de l'étudiant P(parent=TableCell(parent=tr, valuetype='float', value=etu_resultats['rang']), text="{}".format(etu_resultats['rang'])) # Notes for note in etu_resultats['notes']: tc = TableCell(parent=tr) if isinstance(note, list) and len(note) == 1: note = note[0] if isinstance(note, Note): if note.est_note(): tc.setAttribute('valuetype', 'float') tc.setAttribute('value', note.value) tc.setAttribute('stylename', style_note) P(text="{:.2f}".format(note), parent=tc) elif isinstance(note, list): P(text=', '.join([ "{:.2f}".format(n) for n in note if isinstance(n, Note) ]), parent=tc) ods.write(response) return response
def sessionrange(ds,start=None,end=None,tillname="Till"): """ A spreadsheet summarising sessions between the start and end date. """ depts=ds.query(Department).order_by(Department.id).all() depttotals=ds.query(Session,Department,func.sum( Transline.items*Transline.amount)).\ select_from(Session).\ options(undefer('total')).\ options(undefer('actual_total')).\ filter(Session.endtime!=None).\ filter(select([func.count(SessionTotal.sessionid)], whereclause=SessionTotal.sessionid==Session.id).\ correlate(Session.__table__).as_scalar()!=0).\ join(Transaction,Transline,Department).\ order_by(Session.id,Department.id).\ group_by(Session,Department) if start: depttotals=depttotals.filter(Session.date>=start) if end: depttotals=depttotals.filter(Session.date<=end) doc=OpenDocumentSpreadsheet() datestyle=dateStyle(doc) currencystyle=currencyStyle(doc) header=Style(name="ColumnHeader",family="table-cell") header.addElement( ParagraphProperties(textalign="center")) header.addElement( TextProperties(fontweight="bold")) doc.automaticstyles.addElement(header) def colwidth(w): if not hasattr(colwidth,'num'): colwidth.num=0 colwidth.num+=1 width=Style(name="W{}".format(colwidth.num),family="table-column") width.addElement(TableColumnProperties(columnwidth=w)) doc.automaticstyles.addElement(width) return width widthshort=colwidth("2.0cm") widthtotal=colwidth("2.2cm") widthgap=colwidth("0.5cm") table=Table(name=tillname) # Session ID and date table.addElement(TableColumn(numbercolumnsrepeated=2,stylename=widthshort)) # Totals table.addElement(TableColumn(numbercolumnsrepeated=2,stylename=widthtotal)) # Gap table.addElement(TableColumn(stylename=widthgap)) # Departments table.addElement(TableColumn(numbercolumnsrepeated=len(depts), stylename=widthshort)) tr=TableRow() table.addElement(tr) def tcheader(text): tc=TableCell(valuetype="string",stylename=header) tc.addElement(P(stylename=header,text=text)) return tc tr.addElement(tcheader("ID")) tr.addElement(tcheader("Date")) tr.addElement(tcheader("Till Total")) tr.addElement(tcheader("Actual Total")) tr.addElement(TableCell()) for d in depts: tr.addElement(tcheader(d.description)) def tcint(i): """ Integer table cell """ return TableCell(valuetype="float",value=i) def tcdate(d): """ Date table cell """ return TableCell(valuetype="date",datevalue=d,stylename=datestyle) def tcmoney(m): """ Money table cell """ return TableCell(valuetype="currency",currency="GBP",value=str(m), stylename=currencystyle) tr=None prev_s=None for s,d,t in depttotals: if s!=prev_s: prev_s=s tr=TableRow() table.addElement(tr) tr.addElement(tcint(s.id)) tr.addElement(tcdate(s.date)) tr.addElement(tcmoney(s.total)) tr.addElement(tcmoney(s.actual_total)) tr.addElement(TableCell()) di=iter(depts) while True: dept=next(di) if dept==d: tr.addElement(tcmoney(t)) break else: tr.addElement(TableCell()) doc.spreadsheet.addElement(table) filename="{}-summary".format(tillname) if start: filename=filename+"-from-{}".format(start) if end: filename=filename+"-to-{}".format(end) filename=filename+".ods" r=HttpResponse(content_type='application/vnd.oasis.opendocument.spreadsheet') r['Content-Disposition']='attachment; filename={}'.format(filename) doc.write(r) return r
def colloscope_odf(request, classe): """ Affichage du colloscope d'une classe au format OpenDocument """ response = HttpResponse( content_type='application/vnd.oasis.opendocument.spreadsheet') response[ 'Content-Disposition'] = 'attachment; filename="colloscope_{}.ods"'.format( classe.slug) semaines = classe.semaine_set.order_by('debut') creneaux = classe.creneau_set.order_by('enseignement', 'jour', 'debut') colles = classe.colle_set.filter(semaine__in=semaines, creneau__in=creneaux) # On crée le dictionnaire qui à chaque créneau puis à chaque semaine # associe les groupes de colle colloscope = defaultdict(lambda: defaultdict(list)) for colle in colles: colloscope[colle.creneau][colle.semaine].append(colle) ods = OpenDocumentSpreadsheet() # Styles style_entete = Style(parent=ods.automaticstyles, name='cell_entete', family='table-cell') TextProperties(parent=style_entete, fontweight='bold') style_col_semaine = Style(parent=ods.automaticstyles, name='col_semaine', family='table-column') TableColumnProperties(parent=style_col_semaine, columnwidth='1cm') style_col_matiere = Style(parent=ods.automaticstyles, name='col_matiere', family='table-column') TableColumnProperties(parent=style_col_matiere, columnwidth='5cm') style_col_colleur = Style(parent=ods.automaticstyles, name='col_colleur', family='table-column') TableColumnProperties(parent=style_col_colleur, columnwidth='5cm') style_col_salle = Style(parent=ods.automaticstyles, name='col_salle', family='table-column') TableColumnProperties(parent=style_col_salle, columnwidth='2cm') table = Table(name=str(classe), parent=ods.spreadsheet) # Ajout des colonnes d'en-tête fixes entetes_fixes = ("ID", "Matière", "Colleur", "Jour", "Horaire", "Salle") table.addElement(TableColumn(stylename=style_col_semaine)) # ID table.addElement(TableColumn(stylename=style_col_matiere)) # Matière table.addElement(TableColumn(stylename=style_col_colleur)) # Colleur table.addElement(TableColumn()) # Jour table.addElement(TableColumn()) # Horaire table.addElement(TableColumn(stylename=style_col_salle)) # Salle # Ajout des colonnes d'en-tête des semaines for _ in semaines: table.addElement(TableColumn(stylename=style_col_semaine)) # Container pour les lignes d'en-tête th = TableHeaderRows(parent=table) # Ligne d'en-tête avec les semestres au-dessus des semaines tr = TableRow(parent=th) for entete in entetes_fixes: P(parent=TableCell(parent=tr, valuetype='string', numberrowsspanned=2, numbercolumnsspanned=1, stylename=style_entete), text=entete) # On doit savoir combien de semaines se trouvent sur chaque période # pour afficher les en-têtes sur le bon nombre de colonnes nb_semaines = dict([( periode[0], 0, ) for periode in constantes.PERIODE_CHOICES]) for semaine in semaines: nb_semaines[semaine.periode] += 1 # Insertion des titres des périodes for periode_id, periode_nom in constantes.PERIODE_CHOICES: if nb_semaines[periode_id] > 0: P(parent=TableCell(parent=tr, valuetype='string', numbercolumnsspanned=nb_semaines[periode_id], numberrowsspanned=1, stylename=style_entete), text=periode_nom.capitalize()) CoveredTableCell(parent=tr, numbercolumnsrepeated=nb_semaines[periode_id] - 1) tr = TableRow(parent=th) # Ligne d'en-tête avec seulement les semaines # On doit placer des cellules vides pour les case d'en-tête situées # avant les semaines CoveredTableCell(parent=tr, numbercolumnsrepeated=len(entetes_fixes)) # Puis on ajoute les semaines for semaine in semaines: P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text=semaine.numero) # Colles par créneau for creneau in creneaux: tr = TableRow(parent=table) P(parent=TableCell(parent=tr, valuetype='float', value=creneau.pk), text=creneau.pk) P(parent=TableCell(parent=tr, valuetype='string'), text=creneau.matiere) P(parent=TableCell(parent=tr, valuetype='string'), text=creneau.colleur) P(parent=TableCell(parent=tr, valuetype='string'), text=creneau.get_jour_display()) P(parent=TableCell(parent=tr, valuetype='time', timevalue=creneau.debut.strftime("PT%HH%MM%SS")), text=creneau.debut.strftime("%H:%M")) P(parent=TableCell(parent=tr, valuetype='string'), text=creneau.salle) for semaine in semaines: groupes_texte = ','.join([ str(c.groupe) for c in colloscope[creneau][semaine] if c.groupe ]) cell = TableCell(parent=tr) if groupes_texte: cell.valuetype = "string" P(parent=cell, text=groupes_texte) ods.write(response) return response