def generate_ods(data): """ Generate a ODS file. :param data: list-like of dict with the data. :return: """ doc = OpenDocumentSpreadsheet() table = Table() tr = TableRow() colautowidth = Style(name="co1", family="table-column") colautowidth.addElement(TableColumnProperties(useoptimalcolumnwidth=True)) doc.automaticstyles.addElement(colautowidth) for column in data[0].keys(): table.addElement(TableColumn(stylename=colautowidth)) tc = TableCell(valuetype="string", value=column) tc.addElement(P(text=column)) tr.addElement(tc) table.addElement(tr) for row in data: tr = TableRow() for column in row.keys(): tc = TableCell(valuetype="string", value=row[column]) tc.addElement(P(text=row[column])) tr.addElement(tc) table.addElement(tr) file = os.path.join( tempfile.gettempdir(), 'SIGE' + datetime.now().strftime('%Y%m%d%H%M%S%f') + '.ods') doc.spreadsheet.addElement(table) print(doc.automaticstyles.childNodes[0].attributes) doc.save(file) return file
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 __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 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 test_percentage(self): """ Test that an automatic style can refer to a PercentageStyle as a datastylename """ doc = OpenDocumentSpreadsheet() nonze = PercentageStyle(name='N11') nonze.addElement(Number(decimalplaces='2', minintegerdigits='1')) nonze.addElement(Text(text='%')) doc.automaticstyles.addElement(nonze) pourcent = Style(name='pourcent', family='table-cell', datastylename='N11') pourcent.addElement(ParagraphProperties(textalign='center')) pourcent.addElement(TextProperties(attributes={'fontsize':"10pt",'fontweight':"bold", 'color':"#000000" })) doc.automaticstyles.addElement(pourcent) table = Table(name='sheet1') tr = TableRow() tc = TableCell(formula='=AVERAGE(C4:CB62)/2',stylename='pourcent', valuetype='percentage') tr.addElement(tc) table.addElement(tr) doc.spreadsheet.addElement(table) doc.save("TEST.odt") self.saved = True d = load("TEST.odt") result = d.contentxml() self.assertNotEqual(-1, result.find(u'''<number:percentage-style''')) self.assertNotEqual(-1, result.find(u'''style:data-style-name="N11"''')) self.assertNotEqual(-1, result.find(u'''style:name="pourcent"'''))
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 generate_ods(data): """ Generate a ODS file. :param data: list-like of dict with the data. :return: """ doc = OpenDocumentSpreadsheet() table = Table() tr = TableRow() colautowidth = Style(name="co1", family="table-column") colautowidth.addElement(TableColumnProperties(useoptimalcolumnwidth=True)) doc.automaticstyles.addElement(colautowidth) for column in data[0].keys(): table.addElement(TableColumn(stylename=colautowidth)) tc = TableCell(valuetype="string", value=column) tc.addElement(P(text=column)) tr.addElement(tc) table.addElement(tr) for row in data: tr = TableRow() for column in row.keys(): tc = TableCell(valuetype="string", value=row[column]) tc.addElement(P(text=row[column])) tr.addElement(tc) table.addElement(tr) file = os.path.join(tempfile.gettempdir(), 'SIGE' + datetime.now().strftime('%Y%m%d%H%M%S%f') + '.ods') doc.spreadsheet.addElement(table) print(doc.automaticstyles.childNodes[0].attributes) doc.save(file) return file
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 calc(title, xlabel, ylabel, xdata, ydata): from odf.opendocument import OpenDocumentSpreadsheet from odf.text import P from odf.table import Table, TableColumn, TableRow, TableCell outfile = NamedTemporaryFile( mode='wb', suffix='.ods', prefix='eyesCalc_', delete=False) doc=OpenDocumentSpreadsheet() table = Table(name="ExpEYES {0}".format(time.strftime("%Y-%m-%d %Hh%Mm%Ss"))) doc.spreadsheet.addElement(table) ## add rows into the table for i in range(len(xdata)): tr = TableRow() table.addElement(tr) if len(ydata.shape)==1: # single y data tr.addElement(TableCell(valuetype="float", value=str(xdata[i]))) tr.addElement(TableCell(valuetype="float", value=str(ydata[i]))) else: # multiple y data tr.addElement(TableCell(valuetype="float", value=str(xdata[i]))) for j in range(ydata.shape[0]): tr.addElement(TableCell(valuetype="float", value=str(ydata[j][i]))) doc.save(outfile) outfile.close() call("(localc {}&)".format(outfile.name), shell=True) return [outfile]
def output_reqset(self, reqset, reqscont): # Because of a problem with the current OpenOffice versions, # there is the need to sometimes arrange requirements as rows # and sometimes as columns: # It is not possible to define the range of a list input as a # row: it must be a column. # The order dictionary holds the number - which can be # computed in a row or column. def create_reqs_index(srqes): sreqs_index = {} cnt = 0 for req in sreqs: sreqs_index[req] = cnt cnt += 1 return sreqs_index # The topological sort is needed. sreqs = topological_sort(self.topic_set.reqset) # Create the row / column index of each requirement self.sreqs_index = create_reqs_index(sreqs) # Create and save the document calcdoc = OpenDocumentSpreadsheet() self.create_meta(calcdoc, reqscont) self.create_styles(calcdoc) self.create_costs_sheet(calcdoc, sreqs) self.create_deps_sheet(calcdoc, sreqs) self.create_sums_sheet(calcdoc, sreqs) self.create_constants_sheet(calcdoc) self.create_result_sheet(calcdoc, sreqs) calcdoc.save(self.output_filename, True)
def __init__( self, path: str, engine: str | None = None, date_format=None, datetime_format=None, mode: str = "w", storage_options: StorageOptions = None, if_sheet_exists: str | None = None, engine_kwargs: dict[str, Any] | None = None, **kwargs, ): from odf.opendocument import OpenDocumentSpreadsheet if mode == "a": raise ValueError("Append mode is not supported with odf!") super().__init__( path, mode=mode, storage_options=storage_options, if_sheet_exists=if_sheet_exists, engine_kwargs=engine_kwargs, ) engine_kwargs = combine_kwargs(engine_kwargs, kwargs) self.book = OpenDocumentSpreadsheet(**engine_kwargs) self._style_dict: dict[str, str] = {}
def test_percentage(self): """ Test that an automatic style can refer to a PercentageStyle as a datastylename """ doc = OpenDocumentSpreadsheet() nonze = PercentageStyle(name='N11') nonze.addElement(Number(decimalplaces='2', minintegerdigits='1')) nonze.addElement(Text(text='%')) doc.automaticstyles.addElement(nonze) pourcent = Style(name='pourcent', family='table-cell', datastylename='N11') pourcent.addElement(ParagraphProperties(textalign='center')) pourcent.addElement( TextProperties(attributes={ 'fontsize': "10pt", 'fontweight': "bold", 'color': "#000000" })) doc.automaticstyles.addElement(pourcent) table = Table(name='sheet1') tr = TableRow() tc = TableCell(formula='=AVERAGE(C4:CB62)/2', stylename='pourcent', valuetype='percentage') tr.addElement(tc) table.addElement(tr) doc.spreadsheet.addElement(table) doc.save(u"TEST.ods") self.saved = True d = load(u"TEST.ods") result = d.contentxml() # contentxml is supposed to yeld a bytes self.assertNotEqual(-1, result.find(b'''<number:percentage-style''')) self.assertNotEqual(-1, result.find(b'''style:data-style-name="N11"''')) self.assertNotEqual(-1, result.find(b'''style:name="pourcent"'''))
def calc(title, xlabel, ylabel, xdata, ydata): from odf.opendocument import OpenDocumentSpreadsheet from odf.text import P from odf.table import Table, TableColumn, TableRow, TableCell outfile = NamedTemporaryFile(mode='wb', suffix='.ods', prefix='eyesCalc_', delete=False) doc = OpenDocumentSpreadsheet() table = Table( name="ExpEYES {0}".format(time.strftime("%Y-%m-%d %Hh%Mm%Ss"))) doc.spreadsheet.addElement(table) ## add rows into the table for i in range(len(xdata)): tr = TableRow() table.addElement(tr) if len(ydata.shape) == 1: # single y data tr.addElement(TableCell(valuetype="float", value=str(xdata[i]))) tr.addElement(TableCell(valuetype="float", value=str(ydata[i]))) else: # multiple y data tr.addElement(TableCell(valuetype="float", value=str(xdata[i]))) for j in range(ydata.shape[0]): tr.addElement( TableCell(valuetype="float", value=str(ydata[j][i]))) doc.save(outfile) outfile.close() call("(localc {}&)".format(outfile.name), shell=True) return [outfile]
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 _toODSFile(odf_table_list, filename): doc = OpenDocumentSpreadsheet() for t in odf_table_list: doc.spreadsheet.addElement(t) doc.save('/tmp/' + filename, True) return file('/tmp/' + filename + '.ods')
def topic_set_pre(self, topics_set): '''Document setup and output. Because for this document a very specific sort order must be implemented, everything must be done here explicitly - the executor interface can only partially be used.''' self.__calcdoc = OpenDocumentSpreadsheet() self.__create_meta() self.__create_styles()
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()
class ODSOutput(SpreadsheetOutput): def open(self): self.workbook = OpenDocumentSpreadsheet() def _make_cell(self, value): """ Util for creating an ods cell """ if value: try: # See if value parses as a float cell = odf.table.TableCell(valuetype="float", value=float(value)) except ValueError: cell = odf.table.TableCell(valuetype="string") else: cell = odf.table.TableCell(valuetype="Nonetype") p = odf.text.P(text=value) cell.addElement(p) return cell def write_sheet(self, sheet_name, sheet): worksheet = odf.table.Table(name=sheet_name) sheet_header = list(sheet) header_row = odf.table.TableRow() for header in sheet_header: header_row.addElement(self._make_cell(header)) worksheet.addElement(header_row) for sheet_line in sheet.lines: row = odf.table.TableRow() for header in sheet_header: value = sheet_line.get(header) if isinstance(value, str): new_value = ILLEGAL_CHARACTERS_RE.sub("", value) if new_value != value: warn( _("Character(s) in '{}' are not allowed in a spreadsheet cell. Those character(s) will be removed" ).format(value), DataErrorWarning, ) value = new_value row.addElement(self._make_cell(value)) worksheet.addElement(row) self.workbook.spreadsheet.addElement(worksheet) def close(self): self.workbook.save(self.output_name)
def main(): input_dir = os.path.join(PARMA_DIR, "input") doc = OpenDocumentSpreadsheet() table_list = [] table_list.append( convert_FFPtable_day(os.path.join(input_dir, "FFPtable.day"))) table_list.append( convert_FFPtable_USO(os.path.join(input_dir, "FFPtable.uso"))) for table in table_list: doc.spreadsheet.addElement(table) doc.save("parma.ods")
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)
def _create_odf(self): doc = OpenDocumentSpreadsheet() table = Table(name="Table1") for row in self.df.values: tr = TableRow() for val in row: tc = TableCell(valuetype="string") tc.addElement(P(text=val)) tr.addElement(tc) table.addElement(tr) doc.spreadsheet.addElement(table) doc.save(self.fname_odf)
def __init__( self, path: str, engine: Optional[str] = None, mode: str = "w", **engine_kwargs ): from odf.opendocument import OpenDocumentSpreadsheet engine_kwargs["engine"] = engine if mode == "a": raise ValueError("Append mode is not supported with odf!") super().__init__(path, mode=mode, **engine_kwargs) self.book = OpenDocumentSpreadsheet() self._style_dict: Dict[str, str] = {}
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)
class SpreadSheet(object): def __init__(self): self._document = OpenDocumentSpreadsheet() self._sheets = {} def sheet(self, name): if name not in self._sheets: self._sheets[name] = Sheet(name) self._document.spreadsheet.addElement(self._sheets[name]._table) return self._sheets[name] def add_style(self, name, family, styles, **kwargs): style = Style(name=name, family=family, **kwargs) for v in styles: style.addElement(v) self._document.automaticstyles.addElement(style) def add_font(self, fontface): self._document.fontfacedecls.addElement(fontface) def save(self, buf): return self._document.save(buf)
def write_output_data_to_ods(self, output_filename): """Write output data in ODS file. :param output_filename: Path of the output_filename. """ ods_file = OpenDocumentSpreadsheet() table = Table(name=self.output_sheet_name) for row in self.output_data: table_row = TableRow() for val in row: table_cell = TableCell(valuetype="string") table_cell.addElement(P(text=val)) table_row.addElement(table_cell) table.addElement(table_row) ods_file.spreadsheet.addElement(table) ods_file.save(output_filename)
def test_ooo_ns(self): """ Check that ooo exists in namespace declarations """ calcdoc = OpenDocumentSpreadsheet() table = odf.table.Table(name="Costs") forms = odf.office.Forms() form = odf.form.Form( controlimplementation="ooo:com.sun.star.form.component.Form") lb = odf.form.Listbox( controlimplementation="ooo:com.sun.star.form.component.ListBox", dropdown="true", id="control1") form.addElement(lb) forms.addElement(form) table.addElement(forms) # One empty line tr = odf.table.TableRow() table.addElement(tr) tr = odf.table.TableRow() # One empty cell cell = odf.table.TableCell() tr.addElement(cell) cell = odf.table.TableCell() draw = odf.draw.Control(control="control1", height="0.1126in", width="0.798in", x="0.0303in", y="0.0205in", endcelladdress="Costs.B2", endx="0.8283in", endy="0.1331in") cell.addElement(draw) tr.addElement(cell) table.addElement(tr) calcdoc.spreadsheet.addElement(table) result = calcdoc.contentxml( ) # contentxml() is supposed to yeld a bytes self.assertNotEqual( -1, result.find(b'''xmlns:ooo="http://openoffice.org/2004/office"'''))
def save_table(filename, form, datatable): cols = datatable.columnCount() rows = datatable.rowCount() if form == "Text Files (*.odt)": doc = OpenDocumentSpreadsheet() table = Table() for row in range(rows): tr = TableRow() for col in range(cols): tc = TableCell(valuetype='string') data = datatable.model().index(row, col).data() if data is None: data = "" tc.addElement(P(text=data)) tr.addElement(tc) table.addElement(tr) doc.spreadsheet.addElement(table) doc.save(filename, True) elif form == "Text Files (*.docx)": doc = docx.Document() table = doc.add_table(rows=rows, cols=cols) table.style = 'Table Grid' for row in range(rows): for col in range(cols): cell = table.cell(row, col) data = datatable.model().index(row, col).data() if data is None: data = "" cell.text = data doc.save(filename)
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)
def __init__(self, generator: "AQOdsGenerator") -> None: """ Initialize the file generator. @param generator. File generator. """ self.generator_ = generator from odf.opendocument import OpenDocumentSpreadsheet # Fuera rompe deploy self.spread_sheet = OpenDocumentSpreadsheet() self.generator_.set_doc_(self.spread_sheet)
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(Writer): 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 write_table(self, name): table = Table(name=name) tr = TableRow() for header in self.sheet_data[name]["headers"]: tc = TableCell(valuetype="string", stylename="s") tc.addElement(P(text=header)) tr.addElement(tc) table.addElement(tr) for row in self.sheet_data[name]["rows"]: tr = TableRow() c = 0 for col in row: if c >= len(self.sheet_data[name]["colours"]): cell_format = "p" else: cell_format = self.sheet_data[name]["colours"][c] tc = TableCell(valuetype="string", stylename=cell_format) if col is None: col = "NULL" tc.addElement(P(text=col)) tr.addElement(tc) c += 1 table.addElement(tr) self.doc.spreadsheet.addElement(table)
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 __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 __init__( self, path: str, engine: Optional[str] = None, date_format=None, datetime_format=None, mode: str = "w", storage_options: StorageOptions = None, engine_kwargs: Optional[Dict[str, Any]] = None, ): from odf.opendocument import OpenDocumentSpreadsheet if mode == "a": raise ValueError("Append mode is not supported with odf!") super().__init__( path, mode=mode, storage_options=storage_options, engine_kwargs=engine_kwargs, ) self.book = OpenDocumentSpreadsheet() self._style_dict: Dict[str, str] = {}
def test_ooo_ns(self): """ Check that ooo exists in namespace declarations """ calcdoc = OpenDocumentSpreadsheet() table = odf.table.Table(name="Costs") forms = odf.office.Forms() form = odf.form.Form( controlimplementation="ooo:com.sun.star.form.component.Form") lb = odf.form.Listbox( controlimplementation="ooo:com.sun.star.form.component.ListBox", dropdown="true", id="control1") form.addElement(lb) forms.addElement(form) table.addElement(forms) # One empty line tr = odf.table.TableRow() table.addElement(tr) tr = odf.table.TableRow() # One empty cell cell = odf.table.TableCell() tr.addElement(cell) cell = odf.table.TableCell() draw = odf.draw.Control( control="control1", height="0.1126in", width="0.798in", x="0.0303in", y="0.0205in", endcelladdress="Costs.B2", endx="0.8283in", endy="0.1331in") cell.addElement(draw) tr.addElement(cell) table.addElement(tr) calcdoc.spreadsheet.addElement(table) result = unicode(calcdoc.contentxml(),'utf-8') self.assertNotEqual(-1, result.find(u'''xmlns:ooo="http://openoffice.org/2004/office"'''))
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 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 btExportarClick(self, widget): count = self.tvSolicitudes.get_selection().count_selected_rows() #Exportamos todo el treeview si no se han seleccionado filas. if count == 0: self.tvSolicitudes.get_selection().select_all() tree,iter = self.tvSolicitudes.get_selection().get_selected_rows() textdoc = OpenDocumentSpreadsheet() # Start the table, and describe the columns table = Table(name="Solicitudes") for i in iter: #esto funciona aquí, porque no voy eliminando filas del treeview. Por eso en el botón eliminar tuve que hacerlo distinto. expediente = tree.get_value(tree.get_iter(i), 1) persona = tree.get_value(tree.get_iter(i), 4) fecha = tree.get_value(tree.get_iter(i), 0) caja = tree.get_value(tree.get_iter(i), 2) lugar = tree.get_value(tree.get_iter(i), 3) # Create a row (same as <tr> in HTML) tr = TableRow() table.addElement(tr) # Create a cell cell = TableCell() cell.addElement(P(text=expediente)) # The current displayed value tr.addElement(cell) cell4 = TableCell() cell4.addElement(P(text=caja)) tr.addElement(cell4) cell5 = TableCell() cell5.addElement(P(text=lugar)) tr.addElement(cell5) cell2 = TableCell() cell2.addElement(P(text=persona)) tr.addElement(cell2) cell3 = TableCell() cell3.addElement(P(text=fecha)) tr.addElement(cell3) #exportamos las filas seleccionadas else: tree,iter = self.tvSolicitudes.get_selection().get_selected_rows() # ret = [] # for i in iter: # ret.append(tree.get_value(tree.get_iter(i), 0)) textdoc = OpenDocumentSpreadsheet() # Start the table, and describe the columns table = Table(name="Solicitudes") for i in iter: #esto funciona aquí, porque no voy eliminando filas del treeview. Por eso en el botón eliminar tuve que hacerlo distinto. expediente = tree.get_value(tree.get_iter(i), 1) persona = tree.get_value(tree.get_iter(i), 4) fecha = tree.get_value(tree.get_iter(i), 0) caja = tree.get_value(tree.get_iter(i), 2) lugar = tree.get_value(tree.get_iter(i), 3) # Create a row (same as <tr> in HTML) tr = TableRow() table.addElement(tr) # Create a cell cell = TableCell() cell.addElement(P(text=expediente)) # The current displayed value tr.addElement(cell) cell4 = TableCell() cell4.addElement(P(text=caja)) tr.addElement(cell4) cell5 = TableCell() cell5.addElement(P(text=lugar)) tr.addElement(cell5) cell2 = TableCell() cell2.addElement(P(text=persona)) tr.addElement(cell2) cell3 = TableCell() cell3.addElement(P(text=fecha)) tr.addElement(cell3) textdoc.spreadsheet.addElement(table) textdoc.save("Solicitudes_de_Expediente.ods") if sys.platform == 'linux2': os.system("xdg-open Solicitudes_de_Expediente.ods &") else: os.system("start soffice --calc Solicitudes_de_Expediente.ods &")
def make_style(self, tablename=date): #self.doc = load("themplate.ods") self.doc = OpenDocumentSpreadsheet() # Create a style for the table content. One we can modify # later in the word processor. self.font = FontFace( name="Times New Roman", fontadornments="Normal", fontfamilygeneric="roman", fontpitch="variable" ) self.doc.fontfacedecls.addElement( self.font ) self.root_style = Style(name="rootstyle", family="table-cell") self.root_style.addElement( TableCellProperties( wrapoption="wrap", verticalalign="middle", padding="0.049cm", ) ) #self.root_style.addElement( TableRowProperties(breakbefore="auto", useoptimalrowheight="true",rowheight="3cm", ) ) #self.root_style.addElement(ParagraphProperties(numberlines="false", linenumber="0",))# marginleft="0.4cm")) self.root_style.addElement( TextProperties( fontname="Times New Roman", fontnameasian="Times New Roman", fontsize="10pt")) self.doc.styles.addElement( self.root_style ) page = PageLayout( name="page" ) self.doc.automaticstyles.addElement( page ) page.addElement( PageLayoutProperties( margintop="0.499cm", marginbottom="0.499cm", marginleft="2cm", marginright="0.499cm", shadow="none", backgroundcolor="transparent", tablecentering="horizontal", writingmode="lr-tb") ) self.head = Style(name="head", family="table-cell", parentstylename="rootstyle") self.head.addElement( TextProperties(fontweight="bold", fontweightasian="bold", fontsize="12pt")) self.doc.styles.addElement(self.head) self.tablehead = Style(name="tablehead", family="table-cell", parentstylename="rootstyle") self.tablehead.addElement( ParagraphProperties(numberlines="false", linenumber="0", textalign="center")) self.tablehead.addElement( TableCellProperties( border="0.004cm solid #000000", padding="0.199cm", ) ) self.tablehead.addElement( TextProperties(fontweight="bold", fontweightasian="bold", fontsize="12pt")) self.doc.styles.addElement(self.tablehead) self.tablecontents = Style(name="content", family="table-cell", parentstylename="rootstyle") self.tablecontents.addElement( TableCellProperties( border="0.004cm solid #000000", wrapoption="wrap", verticalalign="middle", ) ) self.doc.styles.addElement(self.tablecontents) self.tablemanuf = Style(name="manuf", family="table-cell", parentstylename="rootstyle") self.tablemanuf.addElement( TableCellProperties( border="0.013cm solid #000000", backgroundcolor="#CCCCCC", ) ) self.tablemanuf.addElement(ParagraphProperties( textalign="center" )) self.tablemanuf.addElement( TextProperties(fontweight="bold", fontweightasian="bold", fontsize="14pt" )) self.doc.styles.addElement(self.tablemanuf) # Create automatic styles for the column widths. # We want two different widths, one in inches, the other one in metric. # ODF Standard section 15.9.1 widthname = Style(name="Wname", family="table-column") widthname.addElement(TableColumnProperties(columnwidth="5 cm")) self.doc.automaticstyles.addElement(widthname ) widthdesc = Style(name="Wdesc", family="table-column") widthdesc.addElement(TableColumnProperties(columnwidth="11 cm",useoptimalcolumnwidth ="1")) self.doc.automaticstyles.addElement( widthdesc ) widthcell = Style(name="Wcell", family="table-column") widthcell.addElement(TableColumnProperties(columnwidth="2.3 cm")) widthcell.addElement(ParagraphProperties(numberlines="false", linenumber="0", textalign="end")) self.doc.automaticstyles.addElement(widthcell) #>> Start the table, and describe the columns self.table = Table(name= tablename ) self.table.addElement(TableColumn(numbercolumnsrepeated=1,stylename=widthname)) self.table.addElement(TableColumn(numbercolumnsrepeated=1,stylename=widthdesc)) self.table.addElement(TableColumn(numbercolumnsrepeated=1,stylename=widthcell))
# You should have received a copy of the GNU General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # Søren Roug # This example shows how to do a conditional currency style. We want negative # numbers to show as red and as Australian dollars. from odf.opendocument import OpenDocumentSpreadsheet from odf.style import Style, TextProperties, TableColumnProperties, Map from odf.number import NumberStyle, CurrencyStyle, CurrencySymbol, Number, Text from odf.text import P from odf.table import Table, TableColumn, TableRow, TableCell textdoc = OpenDocumentSpreadsheet() # Create a style for the table content. One we can modify # later in the spreadsheet. tablecontents = Style(name="Large number", family="table-cell") tablecontents.addElement(TextProperties(fontfamily="Arial", fontsize="15pt")) textdoc.styles.addElement(tablecontents) # Create automatic styles for the column widths. widewidth = Style(name="co1", family="table-column") widewidth.addElement( TableColumnProperties(columnwidth="2.8cm", breakbefore="auto")) textdoc.automaticstyles.addElement(widewidth) # Create the styles for $AUD format currency values ns1 = CurrencyStyle(name="positive-AUD", volatile="true") ns1.addElement(CurrencySymbol(language="en", country="AU", text=u"$"))
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
res = cell.getElementsByType(P)[0].firstChild #print dir(res) if 'data' in dir(res): retour['value'] = res.data if 'table:formula' in cell.attributes: retour['formule'] = cell.getAttribute('formula').replace('of:=', '') return retour else: retour['value'] = False else: retour['value'] = False return retour calc = OpenDocumentSpreadsheet() WhiteStyle = Style(name='Blanc', family="table-cell") WhiteStyle.addElement(TextProperties(fontweight="bold", fontfamily="Arial", fontsize="14pt")) lestyle = WhiteStyle dcs = DateStyle(name="dcs", formatsource="AAAA-MM-JJ") widthshort = Style(name="Wshort", family="table-column") widthshort.addElement(TableColumnProperties(columnwidth="5cm")) widthlong = Style(name="Wshort", family="table-column") widthlong.addElement(TableColumnProperties(columnwidth="15cm")) calc.automaticstyles.addElement(dcs) calc.automaticstyles.addElement(WhiteStyle)
model = Object(cnx, opts.model) mod_count = model.search_count([]) logger.info('There are %d record to export' % mod_count) fields = model.fields_get() fields_name = fields.keys() result = model.read(model.search([])) from odf.opendocument import OpenDocumentSpreadsheet from odf.style import Style, TextProperties, ParagraphProperties, TableColumnProperties from odf.text import P from odf.table import Table, TableColumn, TableRow, TableCell 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=opts.model) if opts.title: logger.info('Write row header') tr = TableRow() table.addElement(tr) for f in fields_name: tc = TableCell(valuetype='string') tr.addElement(tc) p = P(stylename=tablecontents, text=unicode(fields[f]['string'], 'utf-8'))
def __init__(self, file, **keywords): BookWriter.__init__(self, file, **keywords) self.native_book = OpenDocumentSpreadsheet()
def odsResponse(inscriptions, noninscrits): """ fabrique un objet de type HttpResponse qui comporte un tableur au format ODS, avec les exportations d'une "barrette" d'AP. @param inscriptions un objet issu de Inscription.objects.all() @param noninscrits une liste d'Etudiants @return un objet de type HttpResponse """ response = HttpResponse(content_type='application/vnd.oasis.opendocument.spreadsheet') now=timezone.now() filename="aperho-{}.ods".format(now.strftime("%Y%m%d-%H%M")) response['Content-Disposition'] = 'attachment; filename={}'.format(filename) doc = OpenDocumentSpreadsheet() # 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")) doc.styles.addElement(tablecontents) # Create automatic styles for the column widths. # We want two different widths, one in inches, the other one in metric. # ODF Standard section 15.9.1 widthshort = Style(name="Wshort", family="table-column") widthshort.addElement(TableColumnProperties(columnwidth="1.7cm")) doc.automaticstyles.addElement(widthshort) widthwide = Style(name="Wwide", family="table-column") widthwide.addElement(TableColumnProperties(columnwidth="1.5in")) doc.automaticstyles.addElement(widthwide) # Start the table, and describe the columns table = Table(name="Inscriptions") table.addElement(TableColumn(numbercolumnsrepeated=3,stylename=widthwide)) tr = TableRow() table.addElement(tr) for title in ['id', 'Eleve_nom', 'Eleve_prenom', 'Eleve_classe', 'Professeur', 'Salle', 'Heure', 'Duree', 'Public_designe', 'Resume','Detail','Autres']: tc = TableCell() tr.addElement(tc) p = P(stylename=tablecontents,text=title) tc.addElement(p) for i in inscriptions: tr = TableRow() table.addElement(tr) for val in [i.pk, i.etudiant.nom, i.etudiant.prenom, i.etudiant.classe, i.cours.enseignant.nom, i.cours.enseignant.salle, i.cours.horaire, i.cours.formation.duree, i.cours.formation.public_designe, i.cours.formation.titre, i.cours.formation.contenu]: tc = TableCell() tr.addElement(tc) p = P(stylename=tablecontents,text=str(val)) tc.addElement(p) ## write something in the last column (Autres) tc = TableCell() tr.addElement(tc) p = P(stylename=tablecontents,text=rdvOrientation(i)) tc.addElement(p) for e in noninscrits: tr = TableRow() table.addElement(tr) for val in [0, e.nom, e.prenom, e.classe, '', '', '', '', '', '', '','']: tc = TableCell() tr.addElement(tc) p = P(stylename=tablecontents,text=str(val)) tc.addElement(p) doc.spreadsheet.addElement(table) output=BytesIO() doc.save(output) response.write(output.getvalue()) return response
def getValues(self, **kw): """ a routine to get measured values as a useful file @param kw keywords; allowed keywords are: - mode: the way you want to get the values The default mode is "ascii", which means that values are formated as ascii lines (space-separated numbers). <BR> Other supported modes are not yet implemented @return a stream with the relevant MIMEtype. """ filename="values-{0}".format(time.strftime("%Y-%m-%d_%H_%M_%S")) if 'mode' in kw: mode=kw['mode'] else: #mode='ascii' mode='ods' if mode=="ascii": ## define response headers cherrypy.response.headers["Content-Type"]="text/ascii;charset=utf-8" cherrypy.response.headers['Content-Disposition'] = 'attachment; filename={}.txt'.format(filename) ## send the data if self.mtype=='t,v': result="" t,v = self.measurements for i in range(len(t)): result+="{0:f} {1:f}\n".format(t[i], v[i]) return result else: return "mode = '%s', measurement type '%s' not supported." %(mode, self.mtype) elif mode=="ods": ## define response headers cherrypy.response.headers["Content-Type"]="application/vnd.oasis.opendocument.spreadsheet" cherrypy.response.headers['Content-Disposition'] = 'attachment; filename={}.ods'.format(filename) ## send the data if self.mtype=='t,v': doc = OpenDocumentSpreadsheet() # Start the table, and describe the columns table = Table(name="Expeyes-Jr {0}".format(time.strftime("%Y-%m-%d %Hh%Mm%Ss"))) ## column titles tr = TableRow() table.addElement(tr) tc = TableCell() tr.addElement(tc) p = P(text='t (ms)') tc.addElement(p) tc = TableCell() tr.addElement(tc) input=self.inp for name in ExpPage.expeyes_inputs: if ExpPage.expeyes_inputs[name]== self.inp: input=name break p = P(text=input+' (V)') tc.addElement(p) ## write values t,v=self.measurements for i in range(len(t)): tr = TableRow() table.addElement(tr) tc = TableCell(valuetype="float", value=str(t[i])) tr.addElement(tc) tc = TableCell(valuetype="float", value=str(v[i])) tr.addElement(tc) doc.spreadsheet.addElement(table) result=io.BytesIO() doc.save(result) return result.getvalue() else: return "mode = '%s', measurement type '%s' not supported." %(mode, self.mtype) return "non-supported mode %s" %mode
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
for variable, examinee, examiners in possibilities: if variables[variable]: examinees[examinee] = examiners 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)
def save(self, filename, i_max = None, j_max = None): ''' save table in ods format ''' if not i_max: i_max = self.table.i_max if not j_max: j_max = self.table.j_max # update cells text self.table.updateTable(i_max, j_max) # create new odf spreadsheet odfdoc = OpenDocumentSpreadsheet() # set direction style rtl = Style(name = "dir", family = "table") if self.table.direction == 'rtl': rtl.addElement(TableProperties(writingmode="rl-tb")) odfdoc.automaticstyles.addElement(rtl) # create the table table = Table(name = "sheet 1", stylename = 'dir') # default style ts = Style(name = "ts", family = "table-cell") ts.addElement(TextProperties(fontfamily = SodsCell().font_family, fontsize = SodsCell().font_size)) odfdoc.styles.addElement(ts) # create columns for j in range(1, j_max): colname = "col" + str(j) c = self.table.getCellAt(0, j) width = c.column_width cs = Style(name = colname, family = "table-column") cs.addElement(TableColumnProperties(columnwidth = width, breakbefore = "auto")) odfdoc.automaticstyles.addElement(cs) table.addElement(TableColumn(stylename = colname, defaultcellstylename = "ts")) # make sure values are up to date # loop and update the cells value for i in range(1, i_max): # create new ods row tr = TableRow() table.addElement(tr) # create default data styles for dates and numbers ncs = NumberStyle(name="ncs") ncs.addElement(Number(decimalplaces="2", minintegerdigits="1", grouping="true")) odfdoc.styles.addElement(ncs) ncs2 = NumberStyle(name="ncs2") ncs2.addElement(Number(decimalplaces="0", minintegerdigits="1", grouping="false")) odfdoc.styles.addElement(ncs2) dcs = DateStyle(name="dcs") dcs.addElement(Year(style='long')) dcs.addElement(Text(text = u'-')) dcs.addElement(Month(style='long')) dcs.addElement(Text(text = u'-')) dcs.addElement(Day(style='long')) odfdoc.styles.addElement(dcs) for j in range(1, j_max): # update the cell text and condition cell = self.table.encodeColName(j) + str(i) c = self.table.getCellAt(i, j) # chose datastylename if c.value_type == 'date': datastylename = "dcs" else: if c.format == "": datastylename = "ncs2" if c.format == "#,##0.00": datastylename = "ncs" # get cell style id if (c.condition): style_id = (datastylename + c.color + c.font_size + c.font_family + c.background_color + c.border_top + c.border_bottom + c.border_left + c.border_right + c.condition_color + c.condition_background_color) else: style_id = (datastylename + c.color + c.font_size + c.font_family + c.background_color + c.border_top + c.border_bottom + c.border_left + c.border_right) # set ods style style_name = self.getStyle(c, cell, datastylename, style_id, odfdoc) # create new ods cell if (c.formula and c.formula[0] == '=' and c.formula[:4] != '=uni'): if self.table.isFloat(c.value): tc = TableCell(valuetype = c.value_type, formula = c.formula, value = float(c.value), stylename = style_name) else: tc = TableCell(valuetype = c.value_type, formula = c.formula, value = 0, stylename = style_name) elif (c.value_type == 'date'): tc = TableCell(valuetype = c.value_type, datevalue = c.date_value, stylename = style_name) elif (c.value_type == 'float') and self.table.isFloat(c.value): tc = TableCell(valuetype = c.value_type, value = float(c.value), stylename = style_name) else: tc = TableCell(valuetype = 'string', stylename = style_name) # set ods text tc.addElement(P(text = unicode(escape(c.text), 'utf-8'))) tr.addElement(tc) odfdoc.spreadsheet.addElement(table) odfdoc.save(filename)
class _ODSWriter(ExcelWriter): engine = "odf" supported_extensions = (".ods",) def __init__( self, path: str, engine: Optional[str] = None, mode: str = "w", **engine_kwargs ): from odf.opendocument import OpenDocumentSpreadsheet engine_kwargs["engine"] = engine if mode == "a": raise ValueError("Append mode is not supported with odf!") super().__init__(path, mode=mode, **engine_kwargs) self.book = OpenDocumentSpreadsheet() self._style_dict: Dict[str, str] = {} def save(self) -> None: """ Save workbook to disk. """ for sheet in self.sheets.values(): self.book.spreadsheet.addElement(sheet) self.book.save(self.path) def write_cells( self, cells: List[ExcelCell], sheet_name: Optional[str] = None, startrow: int = 0, startcol: int = 0, freeze_panes: Optional[Tuple[int, int]] = None, ) -> None: """ Write the frame cells using odf """ from odf.table import Table, TableCell, TableRow from odf.text import P sheet_name = self._get_sheet_name(sheet_name) assert sheet_name is not None if sheet_name in self.sheets: wks = self.sheets[sheet_name] else: wks = Table(name=sheet_name) self.sheets[sheet_name] = wks if validate_freeze_panes(freeze_panes): assert freeze_panes is not None self._create_freeze_panes(sheet_name, freeze_panes) for _ in range(startrow): wks.addElement(TableRow()) rows: DefaultDict = defaultdict(TableRow) col_count: DefaultDict = defaultdict(int) for cell in sorted(cells, key=lambda cell: (cell.row, cell.col)): # only add empty cells if the row is still empty if not col_count[cell.row]: for _ in range(startcol): rows[cell.row].addElement(TableCell()) # fill with empty cells if needed for _ in range(cell.col - col_count[cell.row]): rows[cell.row].addElement(TableCell()) col_count[cell.row] += 1 pvalue, tc = self._make_table_cell(cell) rows[cell.row].addElement(tc) col_count[cell.row] += 1 p = P(text=pvalue) tc.addElement(p) # add all rows to the sheet for row_nr in range(max(rows.keys()) + 1): wks.addElement(rows[row_nr]) def _make_table_cell_attributes(self, cell) -> Dict[str, Union[int, str]]: """Convert cell attributes to OpenDocument attributes Parameters ---------- cell : ExcelCell Spreadsheet cell data Returns ------- attributes : Dict[str, Union[int, str]] Dictionary with attributes and attribute values """ attributes: Dict[str, Union[int, str]] = {} style_name = self._process_style(cell.style) if style_name is not None: attributes["stylename"] = style_name if cell.mergestart is not None and cell.mergeend is not None: attributes["numberrowsspanned"] = max(1, cell.mergestart) attributes["numbercolumnsspanned"] = cell.mergeend return attributes def _make_table_cell(self, cell) -> Tuple[str, Any]: """Convert cell data to an OpenDocument spreadsheet cell Parameters ---------- cell : ExcelCell Spreadsheet cell data Returns ------- pvalue, cell : Tuple[str, TableCell] Display value, Cell value """ from odf.table import TableCell attributes = self._make_table_cell_attributes(cell) val, fmt = self._value_with_fmt(cell.val) pvalue = value = val if isinstance(val, bool): value = str(val).lower() pvalue = str(val).upper() if isinstance(val, datetime.datetime): value = val.isoformat() pvalue = val.strftime("%c") return ( pvalue, TableCell(valuetype="date", datevalue=value, attributes=attributes), ) elif isinstance(val, datetime.date): value = val.strftime("%Y-%m-%d") pvalue = val.strftime("%x") return ( pvalue, TableCell(valuetype="date", datevalue=value, attributes=attributes), ) else: class_to_cell_type = { str: "string", int: "float", float: "float", bool: "boolean", } return ( pvalue, TableCell( valuetype=class_to_cell_type[type(val)], value=value, attributes=attributes, ), ) 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 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_freeze_panes( self, sheet_name: str, freeze_panes: Tuple[int, int] ) -> None: """ Create freeze panes in the sheet. Parameters ---------- sheet_name : str Name of the spreadsheet freeze_panes : tuple of (int, int) Freeze pane location x and y """ from odf.config import ( ConfigItem, ConfigItemMapEntry, ConfigItemMapIndexed, ConfigItemMapNamed, ConfigItemSet, ) config_item_set = ConfigItemSet(name="ooo:view-settings") self.book.settings.addElement(config_item_set) config_item_map_indexed = ConfigItemMapIndexed(name="Views") config_item_set.addElement(config_item_map_indexed) config_item_map_entry = ConfigItemMapEntry() config_item_map_indexed.addElement(config_item_map_entry) config_item_map_named = ConfigItemMapNamed(name="Tables") config_item_map_entry.addElement(config_item_map_named) config_item_map_entry = ConfigItemMapEntry(name=sheet_name) config_item_map_named.addElement(config_item_map_entry) config_item_map_entry.addElement( ConfigItem(name="HorizontalSplitMode", type="short", text="2") ) config_item_map_entry.addElement( ConfigItem(name="VerticalSplitMode", type="short", text="2") ) config_item_map_entry.addElement( ConfigItem( name="HorizontalSplitPosition", type="int", text=str(freeze_panes[0]) ) ) config_item_map_entry.addElement( ConfigItem( name="VerticalSplitPosition", type="int", text=str(freeze_panes[1]) ) ) config_item_map_entry.addElement( ConfigItem(name="PositionRight", type="int", text=str(freeze_panes[0])) ) config_item_map_entry.addElement( ConfigItem(name="PositionBottom", type="int", text=str(freeze_panes[1])) )
def __init__(self): BookWriter.__init__(self) self._native_book = OpenDocumentSpreadsheet()
# # You should have received a copy of the GNU General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from odf.opendocument import OpenDocumentSpreadsheet from odf.style import Style, TextProperties, ParagraphProperties, TableColumnProperties from odf.text import P from odf.table import Table, TableColumn, TableRow, TableCell PWENC = "utf-8" textdoc = OpenDocumentSpreadsheet() # 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) # Create automatic styles for the column widths. # We want two different widths, one in inches, the other one in metric. # ODF Standard section 15.9.1 widthshort = Style(name="Wshort", family="table-column") widthshort.addElement(TableColumnProperties(columnwidth="1.7cm")) textdoc.automaticstyles.addElement(widthshort) widthwide = Style(name="Wwide", family="table-column")
def create_ods(filename): doc = OpenDocumentSpreadsheet() # doc.spreadsheet.addElement(table) # doc.save(filename, True) # add "ods" as suffix doc.save(filename) # not add "ods" as suffix
# Contributor(s): # import os, sys import sqlite from odf.opendocument import OpenDocumentSpreadsheet from odf.style import Style, TextProperties, ParagraphProperties, TableColumnProperties from odf.text import P from odf.table import Table, TableColumn, TableRow, TableCell if len(sys.argv) != 3: print "Usage: sqlite-db table" sys.exit(2) sqldb = sys.argv[1] sqltable = sys.argv[2] textdoc = OpenDocumentSpreadsheet() # 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) # Create automatic styles for the column widths. # We want two different widths, one in inches, the other one in metric. # ODF Standard section 15.9.1 widthshort = Style(name="Wshort", family="table-column") widthshort.addElement(TableColumnProperties(columnwidth="1.7cm")) textdoc.automaticstyles.addElement(widthshort) widthwide = Style(name="Wwide", family="table-column")
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 Save_to_ods: def __init__(self): pass def make_style(self, tablename=date): #self.doc = load("themplate.ods") self.doc = OpenDocumentSpreadsheet() # Create a style for the table content. One we can modify # later in the word processor. self.font = FontFace( name="Times New Roman", fontadornments="Normal", fontfamilygeneric="roman", fontpitch="variable" ) self.doc.fontfacedecls.addElement( self.font ) self.root_style = Style(name="rootstyle", family="table-cell") self.root_style.addElement( TableCellProperties( wrapoption="wrap", verticalalign="middle", padding="0.049cm", ) ) #self.root_style.addElement( TableRowProperties(breakbefore="auto", useoptimalrowheight="true",rowheight="3cm", ) ) #self.root_style.addElement(ParagraphProperties(numberlines="false", linenumber="0",))# marginleft="0.4cm")) self.root_style.addElement( TextProperties( fontname="Times New Roman", fontnameasian="Times New Roman", fontsize="10pt")) self.doc.styles.addElement( self.root_style ) page = PageLayout( name="page" ) self.doc.automaticstyles.addElement( page ) page.addElement( PageLayoutProperties( margintop="0.499cm", marginbottom="0.499cm", marginleft="2cm", marginright="0.499cm", shadow="none", backgroundcolor="transparent", tablecentering="horizontal", writingmode="lr-tb") ) self.head = Style(name="head", family="table-cell", parentstylename="rootstyle") self.head.addElement( TextProperties(fontweight="bold", fontweightasian="bold", fontsize="12pt")) self.doc.styles.addElement(self.head) self.tablehead = Style(name="tablehead", family="table-cell", parentstylename="rootstyle") self.tablehead.addElement( ParagraphProperties(numberlines="false", linenumber="0", textalign="center")) self.tablehead.addElement( TableCellProperties( border="0.004cm solid #000000", padding="0.199cm", ) ) self.tablehead.addElement( TextProperties(fontweight="bold", fontweightasian="bold", fontsize="12pt")) self.doc.styles.addElement(self.tablehead) self.tablecontents = Style(name="content", family="table-cell", parentstylename="rootstyle") self.tablecontents.addElement( TableCellProperties( border="0.004cm solid #000000", wrapoption="wrap", verticalalign="middle", ) ) self.doc.styles.addElement(self.tablecontents) self.tablemanuf = Style(name="manuf", family="table-cell", parentstylename="rootstyle") self.tablemanuf.addElement( TableCellProperties( border="0.013cm solid #000000", backgroundcolor="#CCCCCC", ) ) self.tablemanuf.addElement(ParagraphProperties( textalign="center" )) self.tablemanuf.addElement( TextProperties(fontweight="bold", fontweightasian="bold", fontsize="14pt" )) self.doc.styles.addElement(self.tablemanuf) # Create automatic styles for the column widths. # We want two different widths, one in inches, the other one in metric. # ODF Standard section 15.9.1 widthname = Style(name="Wname", family="table-column") widthname.addElement(TableColumnProperties(columnwidth="5 cm")) self.doc.automaticstyles.addElement(widthname ) widthdesc = Style(name="Wdesc", family="table-column") widthdesc.addElement(TableColumnProperties(columnwidth="11 cm",useoptimalcolumnwidth ="1")) self.doc.automaticstyles.addElement( widthdesc ) widthcell = Style(name="Wcell", family="table-column") widthcell.addElement(TableColumnProperties(columnwidth="2.3 cm")) widthcell.addElement(ParagraphProperties(numberlines="false", linenumber="0", textalign="end")) self.doc.automaticstyles.addElement(widthcell) #>> Start the table, and describe the columns self.table = Table(name= tablename ) self.table.addElement(TableColumn(numbercolumnsrepeated=1,stylename=widthname)) self.table.addElement(TableColumn(numbercolumnsrepeated=1,stylename=widthdesc)) self.table.addElement(TableColumn(numbercolumnsrepeated=1,stylename=widthcell)) def add_rows(self, _tuple, stylename): ''' _tuple example ( ('','',), # 1 row ('','','',), # 2 row ) ''' for _r in _tuple: tr = TableRow() self.table.addElement(tr) for _c in _r: tc = TableCell( stylename= stylename ) tr.addElement(tc) p = P(text = _c ) tc.addElement(p) def add_spanned_row( self, _tuple, stylename, _count_col_spanned = 3): tr = TableRow() self.table.addElement(tr) for _c in _tuple: tc = TableCell( stylename= stylename ) tc = TableCell( stylename= stylename, numbercolumnsspanned= _count_col_spanned, numberrowsspanned = 1 ) tr.addElement(tc) p = P(text = _c ) tc.addElement(p) tr.addElement( CoveredTableCell() ) def add_row( self, _tuple, stylename): tr = TableRow() self.table.addElement(tr) for _c in _tuple: tc = TableCell( stylename= stylename ) tr.addElement(tc) p = P(text = _c ) tc.addElement(p) def add_cell( self, _cell, _table_row, stylename): tc = TableCell( stylename= stylename ) _table_row.addElement(tc) p = P(text = _cell ) tc.addElement(p) def generate_ods(self, path="/home/apkawa/work/test_desu", group=False): self.make_style( tablename = self.category.name ) self.add_spanned_row( (u'OOO "Политехник"',), self.head ) head = ( ( u'phone:','+7 (812) 312-42-38'), ( u'','+7 (812) 970-42-93'), ( u'email:','*****@*****.**'), ( u'www:','http://polytechnik.ru'), ('',), ) self.add_rows( head, self.head ) self.add_row( ( u'Прайс от %s'%date,), self.root_style ) self.add_spanned_row( (self.category.name, ), self.tablemanuf ) self.add_row( ( u'Наименование',u'Описание',u'Цена',), self.tablehead ) manuf = None type_product = 13 for p in self.price: if manuf != p.manufacturer_id and p.manufacturer_id != 233: manuf = p.manufacturer.id self.add_spanned_row( (p.manufacturer.name,) , self.tablemanuf ) if type_product != p.type_product_id and p.type_product_id != 13: type_product = p.type_product_id self.add_spanned_row( ( p.type_product.name,) , self.tablemanuf ) p_desc = p.desc p_cell = ' %.0f %s'%(p.cell, p.valyuta.desc) if p.cell else ' -' if p_desc: self.add_row( ( p.name, p_desc, p_cell ) , self.tablecontents ) elif not p.desc and not p.cell: p_name = re.sub('(<h4>|</h4>)','',p.name) self.add_spanned_row( (p_name,), self.tablehead ) else: tr = TableRow( stylename = self.tablecontents ) self.table.addElement(tr) p_price = ( p.name, p_cell ) #self.add_cell( pl, tr, self.tablecontents, )#numbercolumnsspanned=2, numberrowsspanned = 1 ) tc = TableCell( stylename= self.tablecontents, numbercolumnsspanned=2, numberrowsspanned = 1 ) tr.addElement(tc) p = P(text=p_price[0]) tc.addElement(p) tr.addElement( CoveredTableCell() ) self.add_cell( p_price[1], tr, self.tablecontents ) self.doc.spreadsheet.addElement( self.table ) self.doc.save( path , True) def read_stdout(self): print 'name; desc;cell; manuf;pos;type_product;pos;category_id; img_url' manuf = None type_product = None for p in self.price: if manuf != p.manufacturer_id and p.manufacturer_id != 233: manuf = p.manufacturer.id print '"%s";"%s";\n'%(p.manufacturer.name,p.manufacturer.pos if p.manufacturer.pos else '') if type_product != p.type_product_id and p.type_product_id != 13: type_product = p.type_product_id print '"%s";"%s";\n'%(p.type_product.name, p.type_product.pos if p.type_product.pos else '' ) # 0 1 2 3 4 5 6 7 8 #name_pr desc cell manuf pos type_product pos category_id img_flag print '"%s";"%s";"%s";"%s";"%s";"%s";"%s";"%s";"%s";'%(p.name, p.desc if p.desc else '', '%.0f %s'%(p.cell, p.valyuta.desc), p.manufacturer.name, p.manufacturer.pos, p.type_product.name, p.type_product.pos, p.category_id, p.img_url if p.img_url else '') def connect_base(self, category_id = 202, manufac_name = False): self.base = [] self.category = Category.objects.get(id= category_id ) if manufac_name and type(manufac_name) == type([]): self.price = Price.objects.filter( category = self.category, manufacturer__name__in = manufac_name ).order_by( 'manufacturer__pos','manufacturer', 'type_product__pos','type_product','id' ) elif manufac_name: self.price = Price.objects.filter( category = self.category, manufacturer__name = manufac_name ).order_by( 'manufacturer__pos','manufacturer', 'type_product__pos','type_product','id' ) else: self.price = Price.objects.filter( category = self.category ).order_by( 'manufacturer__pos','manufacturer', 'type_product__pos','type_product','id' ) if not self.price.count(): return False else: return True