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)
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 insertColumn(self, sheetname, columnname, columnnumber): """Inserts a new empty column into the current doc. @param sheetname: The name of the sheet to be added to. @type sheetname: string @param columnname: The name of the new column to be added @type columnname: string @param columnnumber: Where to insert the new column (= how many come before it?) @type columnnumber: int """ sheets = self._doc.spreadsheet.getElementsByType(Table) for sheet in sheets: if sheet.getAttribute('name') == sheetname: rownum = 0 rows = sheet.getElementsByType(TableRow) for row in rows: colNum = 0 cells = row.getElementsByType(TableCell) for cell in cells: if colNum == columnnumber: newCell = TableCell() if rownum == 0: p = P() p.addText(StringUtils.toUnicode(columnname)) newCell.addElement(p) else: p = P() p.addText(StringUtils.toUnicode('')) newCell.addElement(p) row.insertBefore(newCell, cell) colNum += 1 rownum += 1
def insertColumn(self, sheetname, columnname, columnnumber): """Inserts a new empty column into the current doc. @param sheetname: The name of the sheet to be added to. @type sheetname: string @param columnname: The name of the new column to be added @type columnname: string @param columnnumber: Where to insert the new column (= how many come before it?) @type columnnumber: int """ sheets = self._doc.spreadsheet.getElementsByType(Table) for sheet in sheets: if sheet.getAttribute('name') == sheetname: rownum = 0 rows = sheet.getElementsByType(TableRow) for row in rows: colNum = 0 cells = row.getElementsByType(TableCell) for cell in cells: if colNum == columnnumber: newCell = TableCell() if rownum == 0: p = P() p.addText(unicode(columnname)) newCell.addElement(p) else: p = P() p.addText(unicode('')) newCell.addElement(p) row.insertBefore(newCell, cell) colNum += 1 rownum += 1
def addTable(self,tabledata,headers,formater=None): if formater and len(formater)!=len(tabledata): raise ValueError if formater is None: formater = [[""]*len(tabledata[0])]*len(tabledata) table = Table() columns = len(headers) table.addElement(TableColumn(numbercolumnsrepeated=columns)) tr = TableRow() table.addElement(tr) for header in headers: tc = TableCell(stylename="Table") tr.addElement(tc) p = P(stylename=self.tableheaders,text=header) tc.addElement(p) for line,formats in zip(tabledata,formater): tr = TableRow() table.addElement(tr) for column,cformat in zip(line,formats): if cformat == "centerred": cellformat = self.tablecontentscenter elif cformat == "center": cellformat = self.tablecontentscenterred else: cellformat = self.tablecontents tc = TableCell(stylename="Table") tr.addElement(tc) p = P(stylename=cellformat,text=column) tc.addElement(p) self.textdoc.text.addElement(table)
def addTableOnBookmark(self, bookmarkName, tableData, enumerated=False): '''Вставка таблицы перед закладкой ''' table_columns = 3 if enumerated else 2 #Создание и заполнение таблицы table = Table() table.addElement(TableColumn(numbercolumnsrepeated=table_columns)) for index, row in enumerate(tableData): tr = TableRow() table.addElement(tr) if enumerated: tc = TableCell() tr.addElement(tc) tc.addElement(P(text=str(index + 1))) for item in row: tc = TableCell() tr.addElement(tc) tc.addElement( P(text=str(item) if type(item) != QVariant else '')) bookmarks = self.doc.getElementsByType(BookmarkStart) #Вставка таблицы в content.xml for bookmark in bookmarks: if bookmark.getAttribute("name") == bookmarkName: bookmark.parentNode.parentNode.insertBefore( table, bookmark.parentNode) bookmark.parentNode.parentNode.insertBefore( P(text=""), bookmark.parentNode) self.doc.save(root + r"/releasedDocs/Документ", True)
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 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 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 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 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 creerCellule(self, donnee, **kwargs): tc = TableCell(valuetype="string") nbCellulesRecouvertes = kwargs.get('numbercolumnsspanned', None) if nbCellulesRecouvertes: tc = TableCell(valuetype="string", numbercolumnsspanned=int(nbCellulesRecouvertes)) tc.addElement(P(text=str(donnee))) return tc
def row(rec): tr = TableRow() table.addElement(tr) for r in rec: tc = TableCell() tr.addElement(tc) p = P(stylename=tablecontents, text=r) tc.addElement(p)
def addcell(tr, val, lestyle): if val == 'True': val = "Oui" if val == 'False': val = "Non" tc = TableCell(stylename=lestyle) tr.addElement(tc) p = P(text=val) tc.addElement(p)
def addElementToRow(self, element, elementType, tableRow, tablecontents): if elementType == "float": tc = TableCell(valuetype=elementType, value=element.strip()) else: tc = TableCell(valuetype=elementType) tableRow.addElement(tc) p = P(stylename=tablecontents, text=element) tc.addElement(p)
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 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 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 cell(tr, val, style=None): print "[cell] type=%s" % str(type(val)) print "[cell] type=%s" % str(val) if style is None: tc = TableCell(valuetype=valuetype(val), value=str(val)) else: tc = TableCell(stylename=style, valuetype=valuetype(val), value=str(val)) tr.addElement(tc) p = P(stylename=tablecontents, text=str(val)) tc.addElement(p)
def write_captions(self, sheet, table): """ Writes sheet's caption row to table. """ row = TableRow() for caption in sheet.captions: cell = TableCell() cell.addElement(P(text=caption)) row.addElement(cell) table.addElement(row)
def sumtable(): ad = {u"Напряжение" : u' (В)', u"Ток" : u' (А)', u"Мощность" : u' (Вт/c)'} table = Table() table.addElement(TableColumn(numbercolumnsrepeated = len(ampl)+1, stylename = tablestyle)) tr = TableRow() tc = TableCell() tr.addElement(tc) for a in ampl: tr.addElement(ttb(tabletextbold, a)) table.addElement(tr) for antenna in sorted(dictwire[wire].keys()): tr = TableRow() tr.addElement(ttb(tabletextbold, antenna)) table.addElement(tr) for port in sorted(dictwire[wire][antenna].keys()): for m in [u"Напряжение", u"Ток", u"Мощность"]: tr = TableRow() tr.addElement(ttb(tabletextbold, m+ad[m])) if port is not None: tr.addElement(ttb(tabletextbold, port)) table.addElement(tr) for rg in sorted(dictwire[wire][antenna][port].keys()): for k in dictwire[wire][antenna][port][rg].keys(): if k != None: b = sorted(dictwire[wire][antenna][port][rg].keys(), key = len) else: b = dictwire[wire][antenna][port][rg].keys() for distance in b: tr = TableRow() tc = TableCell() try: p = P(text = distance + ', ' + rg) except: p = P(text = rg) tc.addElement(p) tr.addElement(tc) for amplitude in ampl: try: if m == u"Мощность": a = data[dictwire[wire][antenna][port][rg][distance][amplitude][u"Напряжение"]] amu = a.energy((0,len(a.xvalue)), bytime = True) amu = '{0:.03e}'.format(amu) wiretype = a.params['wiretype'] else: a = data[dictwire[wire][antenna][port][rg][distance][amplitude][m]] amu = a.max() amu = '{0:.03f}'.format(amu) wiretype = a.params['wiretype'] except KeyError: amu = u'--' tr.addElement(ttb(tabletext, amu)) table.addElement(tr) return [table, wiretype]
def write_cell(self, row, x): tc = TableCell() x_type = type(x) x_odf_type = ODS_WRITE_FORMAT_COVERSION.get(x_type, "string") tc.setAttrNS(OFFICENS, "value-type", x_odf_type) x_odf_value_token = VALUE_TOKEN.get(x_odf_type, "value") converter = ODS_VALUE_CONVERTERS.get(x_odf_type, None) if converter: x = converter(x) if x_odf_type != 'string': tc.setAttrNS(OFFICENS, x_odf_value_token, x) tc.addElement(P(text=x)) row.addElement(tc)
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 addrow(row,table,tablecontents): tr = TableRow() table.addElement(tr) for rr in row: if str(type(rr))=="<type 'unicode'>": tc = TableCell(valuetype="string") tr.addElement(tc) p = P(stylename=tablecontents,text=rr) tc.addElement(p) elif str(type(rr))=="<type 'float'>" or str(type(rr))=="<type 'int'>" or str(type(rr))=="<class 'decimal.Decimal'>" : tc = TableCell(valuetype="float",value=rr) tr.addElement(tc) elif str(type(rr))=="<type 'NoneType'>": tc = TableCell(valuetype="string") tr.addElement(tc) p = P(stylename=tablecontents,text=unicode(' ',PWENC)) tc.addElement(p) elif str(type(rr))=="<type 'datetime.datetime'>": tc = TableCell(valuetype="string") tr.addElement(tc) p = P(stylename=tablecontents,text=unicode(rr.strftime("%d.%m.%Y") ,PWENC)) tc.addElement(p) else: print str(type(rr)),rr tc = TableCell(valuetype="string") tr.addElement(tc) p = P(stylename=tablecontents,text=unicode(rr,PWENC)) tc.addElement(p) tr.addElement(tc) tr.addElement(tc) return table
def write(self, cell, value, style={}): row, col = cell if row >= self._rows: self._rows = row + 1 if col >= self._cols: self._cols = col + 1 tc = TableCell(stylename=self.style('table-cell', style)) if isinstance(value, Formula): tc.setAttrNS(TABLENS, 'formula', value) tc.setAttrNS(OFFICENS, 'value', '0') tc.setAttrNS(OFFICENS, 'value-type', 'float') tc.addElement(P(text=unicode('0', 'utf-8'))) elif isinstance(value, HTML): tc.setAttrNS(OFFICENS, 'value-type', 'string') self._calc.HTML(html5lib.HTMLParser().parse(value), tc) elif isinstance(value, basestring): tc.setAttrNS(OFFICENS, 'value-type', 'string') tc.addElement(P(text=value)) elif isinstance(value, (float, int)): tc.setAttrNS(OFFICENS, 'value-type', 'float') tc.setAttrNS(OFFICENS, 'value', str(value)) tc.addElement(P(text=str(value))) elif isinstance(value, element.Element): tc.setAttrNS(OFFICENS, 'value-type', 'string') tc.addElement(value) self._cells[cell] = tc
def make_row(self, row): """ For each item in array add a cell to a row """ tr = TableRow() for cell_text in row: try: #i = int(cell_text) tc = TableCell(formula=cell_text) except: tc = TableCell() txt = P(text=cell_text) tc.addElement(txt) tr.addElement(tc) return tr
def NameDatePair(self, a, b) : table = Table(name="t") table.addElement(TableColumn(numbercolumnsrepeated="1", stylename="widecolumn")) table.addElement(TableColumn(numbercolumnsrepeated="1", stylename="narrowcolumn")) tr = TableRow() tc = TableCell(valuetype="string") tc.addElement(P(text=a,stylename="Name")) tr.addElement(tc) tc = TableCell(valuetype="string") tc.addElement(P(text=b,stylename="RightItalic")) tr.addElement(tc) table.addElement(tr) return table
def addTable(self, content, cell_style, column_styles=[]): cell_style = getattr(self, cell_style, None) table = Table() for style in column_styles: if "stylename" in style.keys(): style["stylename"] = getattr(self, style["stylename"], None) table.addElement(TableColumn(**style)) for row in content: tr = TableRow() table.addElement(tr) for cell in row: tc = TableCell() tr.addElement(tc) p = P(stylename=cell_style, text=cell) tc.addElement(p) self.document.text.addElement(table)
def skills(self) : t = self.doc.text t.addElement(P(text='RELEVANT SKILLS', stylename="Heading")) table = Table(name="skills-table") col = 0 skills_cols = int(self.config.fetch('skills_cols')) table.addElement(TableColumn(numbercolumnsrepeated=skills_cols)) for skill in Resume.skills(self) : if col % skills_cols == 0 : tr = TableRow() table.addElement(tr) tc = TableCell(valuetype="string") tc.addElement(P(text=skill,stylename="List")) tr.addElement(tc) col += 1 t.addElement(table)
def write_row(self, sheet_row, table): """ Appends ``sheet_row`` data into table. """ row = TableRow() for field in sheet_row: if isinstance(field, datetime.datetime): field = unicode(field.strftime('%Y-%m-%d %H:%M:%S')) elif isinstance(field, datetime.date): field = unicode(field.strftime('%Y-%m-%d')) elif not isinstance(field, unicode): field = unicode(field) cell = TableCell() cell.addElement(P(text=field)) row.addElement(cell) table.addElement(row)
def write_cell(self, row, cell): tc = TableCell() cell_type = type(cell) cell_odf_type = ODS_WRITE_FORMAT_COVERSION.get(cell_type, "string") tc.setAttrNS(OFFICENS, "value-type", cell_odf_type) cell_odf_value_token = VALUE_TOKEN.get(cell_odf_type, "value") converter = ODS_VALUE_CONVERTERS.get(cell_odf_type, None) if converter: cell = converter(cell) if cell_odf_type != 'string': tc.setAttrNS(OFFICENS, cell_odf_value_token, cell) tc.addElement(P(text=cell)) else: lines = cell.split('\n') for line in lines: tc.addElement(P(text=line)) row.addElement(tc)
def write_cell(self, value, **kwargs): if "numbercolumnsspanned" in kwargs or "numberrowsspanned" in kwargs: kwargs.setdefault("numberrowsspanned", "1") kwargs.setdefault("numbercolumnsspanned", "1") cell = TableCell(**kwargs) cell.setAttrNS(OFFICENS, "value-type", "string") if isinstance(value, Element): para = P() para.addElement(value) cell.addElement(para) else: for line in value.split("\n"): cell.addElement(P(text=line)) self._row.addElement(cell)
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 addTable(self, content, cell_style, column_styles=[]): """ """ cell_style = getattr(self, cell_style, None) table = Table() for style in column_styles: if "stylename" in style.keys(): style["stylename"] = getattr(self, style["stylename"], None) table.addElement(TableColumn(**style)) for row in content: tr = TableRow() table.addElement(tr) for cell in row: tc = TableCell() tr.addElement(tc) p = P(stylename=cell_style,text=cell) tc.addElement(p) self.document.text.addElement(table)
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 add_attribute_row(self, table, key, value): """ Add a two cell row to the table """ boldstyle = Style(name="Bold",family="text") boldstyle.addElement(TextProperties(attributes={'fontweight':"bold"})) title_span = Span(stylename=boldstyle, text=key) pt = P(text='') pt.addElement(title_span) tr = TableRow() tc = TableCell(valuetype='string') tc.addElement(pt) tr.addElement(tc) tc = TableCell(valuetype='string') tc.addElement(P(text=value)) tr.addElement(tc) table.addElement(tr)
def write_text(): """Write to output file ordinary elements. This function is called every tame, we collect whole paragraph or block of elements in 'string_to_write' We write every block or paragraph in it's own cell in the first column of output file. After writing we shift down current row and clean 'string_to_write' in order to collect next elements. """ global string_to_write global header_level global ordered global bullet global table global separator global content row = TableRow() cell = TableCell() if header_level != 0 and header_level > 0: if header_level > (len(header) - 1): # if there are headers with lvl bigger than 2 for i in range( len(header), header_level + 1): # creating names for headers with lvl bigger than 2 header.append('header' + str(i)) add_style(cell, header[header_level]) if header_level == separator: # if separator was set, we will create new sheet in document if table.hasChildNodes(): write_sheet() table = Table( name=string_to_write ) # creating new sheet with separating header as name else: add_style(cell, simple_text) if bullet: string_to_write = '- ' + string_to_write if ordered > 0: string_to_write = str(ordered) + ') ' + string_to_write ordered = ordered + 1 content.addText(string_to_write) cell.addElement(content) content = P() count_height(row, cell) row.addElement(cell) table.addElement(row) string_to_write = ''
def write_cell(self, row, cell): """write a native cell""" cell_to_be_written = TableCell() cell_type = type(cell) cell_odf_type = ODS_WRITE_FORMAT_COVERSION.get(cell_type, "string") cell_to_be_written.setAttrNS(OFFICENS, "value-type", cell_odf_type) cell_odf_value_token = VALUE_TOKEN.get(cell_odf_type, "value") converter = ODS_VALUE_CONVERTERS.get(cell_odf_type, None) if converter: cell = converter(cell) if cell_odf_type != 'string': cell_to_be_written.setAttrNS(OFFICENS, cell_odf_value_token, cell) cell_to_be_written.addElement(P(text=cell)) else: lines = cell.split('\n') for line in lines: cell_to_be_written.addElement(P(text=line)) row.addElement(cell_to_be_written)
def writerow(self, items): self.exrow += 1 #pass # If there is and image in the row, make the row high textrow = True for item in items: if isinstance(item, np.ndarray): textrow = False break if textrow: tr = TableRow(stylename=self.itemRowStyle1) else: tr = TableRow(stylename=self.itemRowStyle3) cells = "ABCDEFGHIJKLM" for n in range(len(items)): if isinstance(items[n], (int, np.int64)): tc = TableCell(valuetype="float", value=str(items[n]), stylename="cellStyle1") p = P(text=items[n]) elif isinstance(items[n], float): tc = TableCell(valuetype="float", value=str("%4.1f"%items[n]), stylename="cellStyle1") p = P(text=items[n]) elif isinstance(items[n], np.ndarray): tc = TableCell(stylename="cellStyle1") fname = tempfile.mktemp(".jpg") sf=0.08 im = items[n] imageio.imwrite(fname, items[n]) f = draw.Frame(endcelladdress="import.%s%d"%(cells[n],self.exrow),endx="%dmm"%int(sf*im.shape[1]), endy="%dmm"%int(sf*im.shape[0])) tc.addElement(f) href=self.doc.addPicture(fname) i = draw.Image(href=href, type="simple", show="embed", actuate="onLoad") f.addElement(i) p = P(text="") i.addElement(p) else: tc = TableCell(stylename="cellStyle1") #empty cell p = P(text=items[n]) tc.addElement(p) tr.addElement(tc) self.table.addElement(tr) return
def create_odf_table_row(data, first=""): """ returns a odt table row that contains the passed data in odf table cells input: first style scheme of the first row's cells output: row the created table row containing cells with corresponding data """ row = TableRow() for i, item in enumerate(data): # we need to distinguish between first column, middle columns and last # columns. The first and the last have outer borders, while the middle # have not. If we draw the first row, skip this and use the passed # style. if not first: # first if i == 0: style = "col_left" # last elif i == (len(data) - 1): style = "col_right" # middle else: style = "col_middle" else: style = first logger.debug("cell content (i=%d):%s, style=%s", i, item, style) cell = TableCell(valuetype='string', stylename=style) cell.addElement(P(text=item, stylename="default")) row.addElement(cell) return row
def create_odf_table_row(data, first=""): """ returns a odt table row that contains the passed data in odf table cells input: first style scheme of the first row's cells output: row the created table row containing cells with corresponding data """ row = TableRow() for i, item in enumerate(data): # we need to distinguish between first column, middle columns and last # columns. The first and the last have outer borders, while the middle # have not. If we draw the first row, skip this and use the passed # style. if not first: # first if i == 0: style = "col_left" # last elif i == (len(data)-1): style = "col_right" # middle else: style = "col_middle" else: style = first logger.debug("cell content (i=%d):%s, style=%s", i, item, style) cell = TableCell(valuetype= 'string', stylename=style) cell.addElement(P(text=item, stylename="default")) row.addElement(cell) return row
def addtable(self, name, hdr): self.table = Table(name=str(name)) self.doc.spreadsheet.addElement(self.table) for h in hdr[:-2]: tcol = TableColumn(stylename=self.colStyle30) self.table.addElement(tcol) tcol = TableColumn(stylename=self.colStyle40) self.table.addElement(tcol) tcol = TableColumn(stylename=self.colStyle200) self.table.addElement(tcol) self.exrow=1 tr = TableRow() for item in hdr: tc = TableCell(stylename="hdrStyle") #empty cell tr.addElement(tc) p = P(text=item) tc.addElement(p) self.table.addElement(tr) return
def write_cell(self, row, cell): """write a native cell""" cell_to_be_written = TableCell() cell_type = type(cell) 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: cell = converter_func(cell) if cell_odf_type != 'string': cell_to_be_written.setAttrNS(OFFICENS, cell_odf_value_token, cell) cell_to_be_written.addElement(P(text=cell)) else: lines = cell.split('\n') for line in lines: cell_to_be_written.addElement(P(text=line)) row.addElement(cell_to_be_written)
def write_image(image): """Write to output file image elements. Since, element with title 'Image' has special structure of 'c'(Content) field, that looks like: [[0], [1], [2]] where: [0] - list of attributes: identifier, classes, key-value pairs: ['id', [], [ ... , ['weight', '...in'], ['height', '...in'], ... ] - we get sizes there. [1] - caption. [2] - ['src', 'title'] - source and title of image. we should parse it especially. Args: image - element with title 'Image'. """ global image_counter global saved_hr if image_counter == -1: return if image_counter == 0: saved_hr = load_images(args.input, ods) if len(saved_hr) == 0: image_counter = -1 return if string_to_write: write_text() row = TableRow() cell = TableCell() w, h = count_size(image['c'][0][2], row) frame = Frame(width=w, height=h) img = Image(href=saved_hr[image_counter]) table.addElement(row) row.addElement(cell) cell.addElement(frame) frame.addElement(img) image_counter = image_counter + 1
def generate_row(datetime, location, extra, acolytes): # Datum und Uhrzeit formatieren date_string = datetime.strftime("%d.%m.%Y") time_string = datetime.strftime("%H:%M") # Neue TableRow erstellen und einfügen row = TableRow() table.addElement(row) # Datum - Zeit Zelle anlegen date_time_cell = TableCell() date_time_cell.addElement(P(stylename=center, text=date_string)) date_time_cell.addElement(P(stylename=center_bold, text=time_string)) # Ort - Information Zelle anlegen location_extra_cell = TableCell() location_extra_cell.addElement(P(stylename=center_bold, text=location)) location_extra_cell.addElement(P(stylename=center, text=extra)) # Messdiener Zelle anlegen acolytes_cell = TableCell() # Messdiener nach Rolle sortiert auflisten for role_name in acolytes: p = P(stylename=left) p.addElement(Span(stylename=bold_style, text=f"{role_name}: ")) p.addText(text=', '.join(acolytes[role_name])) acolytes_cell.addElement(p) # Zellen zur TableRow hinzufügen row.addElement(date_time_cell) row.addElement(location_extra_cell) row.addElement(acolytes_cell) # TableRow zurückgeben return row
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)
def openSpreadsheet(self): """(Re)Loads the spreadsheet.""" self._doc = load(self._filepath) rows = self._doc.spreadsheet.getElementsByType(TableRow) dataWidth = 1 # Determine data-width (as opposed to trailing blank cells) cells = rows[0].getElementsByType(TableCell) for cell in cells[1:]: pl = cell.getElementsByType(P) if len(pl) > 0 and (pl[0].firstChild) and len( StringUtils.toUnicode(pl[0].firstChild)) > 0: dataWidth += 1 else: break # Expand out / decompress repeated cells (e.g. number-columns-repeated="2") for row in rows: cells = row.getElementsByType(TableCell) colNum = 0 for cell in cells: if colNum < dataWidth: repeated = int( cell.getAttribute('numbercolumnsrepeated') or 0) pl = cell.getElementsByType(P) if repeated > 1: if len(pl) > 0 and pl[0].firstChild and len( StringUtils.toUnicode(pl[0].firstChild)) > 0: for i in range(repeated): c = TableCell() p = P() p.addText( StringUtils.toUnicode(pl[0].firstChild)) c.addElement(p) row.insertBefore(c, cell) row.removeChild(cell) else: for i in range(min(repeated, dataWidth - colNum)): c = TableCell() p = P() p.addText(StringUtils.toUnicode('')) c.addElement(p) row.insertBefore(c, cell) row.removeChild(cell) else: row.removeChild(cell) colNum += 1 # Add a constant 3 trailing columns for i in range(3): c = TableCell() p = P() p.addText(StringUtils.toUnicode('')) c.addElement(p) row.addElement(c)
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 openSpreadsheet(self): """(Re)Loads the spreadsheet.""" self._doc = load(self._filepath) rows = self._doc.spreadsheet.getElementsByType(TableRow) dataWidth = 1 # Determine data-width (as opposed to trailing blank cells) cells = rows[0].getElementsByType(TableCell) for cell in cells[1:]: pl = cell.getElementsByType(P) if len(pl) > 0 and (pl[0].firstChild) and len(unicode(pl[0].firstChild)) > 0: dataWidth += 1 else: break # Expand out / decompress repeated cells (e.g. number-columns-repeated="2") for row in rows: cells = row.getElementsByType(TableCell) colNum = 0 for cell in cells: if colNum < dataWidth: repeated = int(cell.getAttribute('numbercolumnsrepeated') or 0) pl = cell.getElementsByType(P) if repeated > 1: if len(pl) > 0 and (pl[0].firstChild) and len(unicode(pl[0].firstChild)) > 0: for i in range(repeated): c = TableCell() p = P() p.addText(unicode(pl[0].firstChild)) c.addElement(p) row.insertBefore(c, cell) row.removeChild(cell) else: for i in range(min(repeated, dataWidth-colNum)): c = TableCell() p = P() p.addText(unicode('')) c.addElement(p) row.insertBefore(c, cell) row.removeChild(cell) else: row.removeChild(cell) colNum += 1 # Add a constant 3 trailing columns for i in range(3): c = TableCell() p = P() p.addText(unicode('')) c.addElement(p) row.addElement(c)
def _toODSTable(v_table): # generate an ods file to download # input: Object VoteTable # output: Object ods.table table= Table(name=v_table.title) row_head = v_table.row_head col_head = v_table.col_head table_body = v_table.table_body # Render column head if it is a 2D table if v_table.is2D(): table.name = '2D' tr= TableRow() table.addElement(tr) td= TableCell() td.addElement(P(text='Head')) tr.addElement(td) for headcell in v_table.col_head: td= TableCell() td.addElement(P(text=headcell.content)) tr.addElement(td) for cursorRow in v_table.table_with_row: tr= TableRow() table.addElement(tr) td= TableCell() td.addElement(P(text=cursorRow['row_head'].content)) tr.addElement(td) for val in cursorRow['row_body']: td= TableCell() td.addElement(P(text=val)) tr.addElement(td) #myFile= tempfile.TemporaryFile('/tmp/') #doc.save('/tmp/test', True) return table
def addrow(row, table, tablecontents): tr = TableRow() table.addElement(tr) for rr in row: if str(type(rr)) == "<type 'unicode'>": tc = TableCell(valuetype="string") tr.addElement(tc) p = P(stylename=tablecontents, text=rr) tc.addElement(p) elif str(type(rr)) == "<type 'float'>" or str( type(rr)) == "<type 'int'>" or str( type(rr)) == "<class 'decimal.Decimal'>": tc = TableCell(valuetype="float", value=rr) tr.addElement(tc) elif str(type(rr)) == "<type 'NoneType'>": tc = TableCell(valuetype="string") tr.addElement(tc) p = P(stylename=tablecontents, text=unicode(' ', PWENC)) tc.addElement(p) elif str(type(rr)) == "<type 'datetime.datetime'>": tc = TableCell(valuetype="string") tr.addElement(tc) p = P(stylename=tablecontents, text=unicode(rr.strftime("%d.%m.%Y"), PWENC)) tc.addElement(p) else: print str(type(rr)), rr tc = TableCell(valuetype="string") tr.addElement(tc) p = P(stylename=tablecontents, text=unicode(rr, PWENC)) tc.addElement(p) tr.addElement(tc) tr.addElement(tc) return table
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
# Create automatic style for the price cells. moneycontents = Style(name="ce1", family="table-cell", parentstylename=tablecontents, datastylename="main-AUD") textdoc.automaticstyles.addElement(moneycontents) # Start the table, and describe the columns table = Table(name="Currency colours") # Create a column (same as <col> in HTML) Make all cells in column default to currency table.addElement(TableColumn(stylename=widewidth, defaultcellstylename="ce1")) # Create a row (same as <tr> in HTML) tr = TableRow() table.addElement(tr) # Create a cell with a negative value. It should show as red. cell = TableCell(valuetype="currency", currency="AUD", value="-125") cell.addElement(P(text=u"$-125.00")) # The current displayed value tr.addElement(cell) # Create a row (same as <tr> in HTML) tr = TableRow() table.addElement(tr) # Create another cell but with a positive value. It should show in black cell = TableCell(valuetype="currency", currency="AUD", value="123") cell.addElement(P(text=u"$123.00")) # The current displayed value tr.addElement(cell) textdoc.spreadsheet.addElement(table) textdoc.save("currency.ods")
widthwide = Style(name="Wwide", family="table-column") widthwide.addElement(TableColumnProperties(columnwidth="1.5in")) textdoc.automaticstyles.addElement(widthwide) # Start the table, and describe the columns table = Table(name=sqltable) #table.addElement(TableColumn(numbercolumnsrepeated=4,stylename=widthshort)) #table.addElement(TableColumn(numbercolumnsrepeated=3,stylename=widthwide)) cx = sqlite.connect(sqldb) cu = cx.cursor() cu.execute("select * from %s" % sqltable) for row in cu.fetchall(): tr = TableRow() table.addElement(tr) for val in row: tc = TableCell() tr.addElement(tc) if type(val) == type(''): textval = unicode(val,'utf-8') else: textval = str(val) p = P(stylename=tablecontents,text=textval) tc.addElement(p) cx.close() textdoc.spreadsheet.addElement(table) textdoc.save(sqltable, True)
def insert_table_(self, ar, column_names=None, table_width=180): # logger.info("20160330 insert_table(%s)", ar) ar.setup_from(self.ar) columns, headers, widths = ar.get_field_info(column_names) widths = map(int, widths) tw = sum(widths) # specifying relative widths doesn't seem to work (and that's # a pity because absolute widths requires us to know the # table_width). use_relative_widths = False if use_relative_widths: width_specs = ["%d*" % (w * 100 / tw) for w in widths] else: width_specs = ["%dmm" % (table_width * w / tw) for w in widths] doc = OpenDocumentText() def add_style(**kw): st = Style(**cleankw(kw)) doc.styles.addElement(st) self.my_styles.append(st) return st table_style_name = str(ar.actor) st = add_style(name=table_style_name, family="table", parentstylename="Default") st.addElement( TableProperties(align="margins", maybreakbetweenrows="0")) # create some *visible* styles st = add_style(name="Table Contents", family="paragraph", parentstylename="Default") st.addElement(ParagraphProperties(numberlines="false", linenumber="0")) st = add_style(name="Number Cell", family="paragraph", parentstylename="Table Contents") st.addElement(ParagraphProperties( numberlines="false", textalign="end", justifysingleword="true", linenumber="0")) dn = "Table Column Header" st = self.stylesManager.styles.getStyle(dn) if st is None: st = add_style(name=dn, family="paragraph", parentstylename="Table Contents") st.addElement( ParagraphProperties(numberlines="false", linenumber="0")) st.addElement(TextProperties(fontweight="bold")) dn = "Bold Text" st = self.stylesManager.styles.getStyle(dn) if st is None: st = add_style(name=dn, family="text", parentstylename="Default") #~ st = add_style(name=dn, family="text") st.addElement(TextProperties(fontweight="bold")) if False: dn = "L1" st = self.stylesManager.styles.getStyle(dn) if st is None: st = ListStyle(name=dn) doc.styles.addElement(st) p = ListLevelProperties( listlevelpositionandspacemode="label-alignment") st.addElement(p) #~ label-followed-by="listtab" text:list-tab-stop-position="1.27cm" fo:text-indent="-0.635cm" fo:margin-left="1.27cm"/> p.addElement(ListLevelLabelAlignment(labelfollowedby="listtab", listtabstopposition="1.27cm", textindent="-0.635cm", marginleft="1.27cm" )) self.my_styles.append(st) #~ list_style = add_style(name=dn, family="list") bullet = text.ListLevelStyleBullet( level=1, stylename="Bullet_20_Symbols", bulletchar=u"•") #~ bullet = text.ListLevelStyleBullet(level=1,stylename="Bullet_20_Symbols",bulletchar=u"*") #~ <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" text:bullet-char="•"> st.addElement(bullet) # create some automatic styles def add_style(**kw): st = Style(**cleankw(kw)) doc.automaticstyles.addElement(st) self.my_automaticstyles.append(st) return st cell_style = add_style(name="Lino Cell Style", family="table-cell") cell_style.addElement(TableCellProperties( paddingleft="1mm", paddingright="1mm", paddingtop="1mm", paddingbottom="0.5mm", border="0.002cm solid #000000")) header_row_style = add_style( name="Lino Header Row", family="table-row", parentstylename=cell_style) header_row_style.addElement( TableRowProperties(backgroundcolor="#eeeeee")) total_row_style = add_style( name="Lino Total Row", family="table-row", parentstylename=cell_style) total_row_style.addElement( TableRowProperties(backgroundcolor="#ffffff")) table = Table(name=table_style_name, stylename=table_style_name) table_columns = TableColumns() table.addElement(table_columns) table_header_rows = TableHeaderRows() table.addElement(table_header_rows) table_rows = TableRows() table.addElement(table_rows) # create table columns and automatic table-column styles for i, fld in enumerate(columns): #~ print 20120415, repr(fld.name) name = str(ar.actor) + "." + str(fld.name) cs = add_style(name=name, family="table-column") if use_relative_widths: cs.addElement( TableColumnProperties(relcolumnwidth=width_specs[i])) else: cs.addElement( TableColumnProperties(columnwidth=width_specs[i])) #~ cs.addElement(TableColumnProperties(useoptimalcolumnwidth='true')) #~ k = cs.getAttribute('name') #~ renderer.stylesManager.styles[k] = toxml(e) #~ doc.automaticstyles.addElement(cs) #~ self.my_automaticstyles.append(cs) table_columns.addElement(TableColumn(stylename=name)) def fldstyle(fld): #~ if isinstance(fld,ext_store.VirtStoreField): #~ fld = fld.delegate if isinstance(fld, NumberFieldElement): return "Number Cell" return "Table Contents" def value2cell(ar, i, fld, val, style_name, tc): # if i == 0: # logger.info("20160330a value2cell(%s, %s)", fld.__class__, val) txt = fld.value2html(ar, val) # if i == 0: # logger.info("20160330b value2cell(%s)", E.tostring(txt)) p = text.P(stylename=style_name) html2odf(txt, p) try: tc.addElement(p) except Exception as e: dd.logger.warning("20120614 addElement %s %s %r : %s", i, fld, val, e) #~ print 20120614, i, fld, val, e #~ yield P(stylename=tablecontents,text=text) # create header row #~ hr = TableRow(stylename=HEADER_ROW_STYLE_NAME) hr = TableRow(stylename=header_row_style) table_header_rows.addElement(hr) for h in headers: #~ for fld in fields: #~ tc = TableCell(stylename=CELL_STYLE_NAME) tc = TableCell(stylename=cell_style) tc.addElement(text.P( stylename="Table Column Header", #~ text=force_text(fld.field.verbose_name or fld.name))) text=force_text(h))) hr.addElement(tc) sums = [fld.zero for fld in columns] for row in ar.data_iterator: #~ for grp in ar.group_headers(row): #~ raise NotImplementedError() tr = TableRow() has_numeric_value = False for i, fld in enumerate(columns): #~ tc = TableCell(stylename=CELL_STYLE_NAME) tc = TableCell(stylename=cell_style) #~ if fld.field is not None: v = fld.field._lino_atomizer.full_value_from_object(row, ar) stylename = fldstyle(fld) if v is None: tc.addElement(text.P(stylename=stylename, text='')) else: value2cell(ar, i, fld, v, stylename, tc) nv = fld.value2num(v) if nv != 0: sums[i] += nv has_numeric_value = True #~ sums[i] += fld.value2num(v) tr.addElement(tc) if has_numeric_value or not ar.actor.hide_zero_rows: table_rows.addElement(tr) if not ar.actor.hide_sums: if sums != [fld.zero for fld in columns]: tr = TableRow(stylename=total_row_style) table_rows.addElement(tr) sums = {fld.name: sums[i] for i, fld in enumerate(columns)} for i, fld in enumerate(columns): tc = TableCell(stylename=cell_style) stylename = fldstyle(fld) p = text.P(stylename=stylename) e = fld.format_sum(ar, sums, i) html2odf(e, p) tc.addElement(p) #~ if len(txt) != 0: #~ msg = "html2odf() returned " #~ logger.warning(msg) #~ txt = tuple(html2odf(fld.format_sum(ar,sums,i),p)) #~ assert len(txt) == 1 #~ tc.addElement(text.P(stylename=stylename,text=txt[0])) tr.addElement(tc) doc.text.addElement(table) return toxml(table)
def insert_table_(self,ar,column_names=None,table_width=180): ar.setup_from(self.ar) columns, headers, widths = ar.get_field_info(column_names) widths = map(int,widths) tw = sum(widths) """ specifying relative widths doesn't seem to work (and that's a pity because absolute widths requires us to know the table_width). """ use_relative_widths = False if use_relative_widths: width_specs = ["%d*" % (w*100/tw) for w in widths] #~ width_specs = [(w*100/tw) for w in widths] else: #~ total_width = 180 # suppose table width = 18cm = 180mm width_specs = ["%dmm" % (table_width*w/tw) for w in widths] #~ else: #~ width_specs = [] #~ for w in widths: #~ if w.endswith('%'): #~ mm = float(w[:-1]) * table_width / 100 #~ width_specs.append("%dmm" % mm) #~ else: #~ print 20120419, width_specs doc = OpenDocumentText() def add_style(**kw): st = Style(**kw) doc.styles.addElement(st) self.my_styles.append(st) return st table_style_name = str(ar.actor) st = add_style(name=table_style_name, family="table",parentstylename="Default") st.addElement(TableProperties(align="margins", maybreakbetweenrows="0")) # create some *visible* styles st = add_style(name="Table Contents", family="paragraph",parentstylename="Default") st.addElement(ParagraphProperties(numberlines="false", linenumber="0")) st = add_style(name="Number Cell", family="paragraph",parentstylename="Table Contents") st.addElement(ParagraphProperties(numberlines="false", textalign="end", justifysingleword="true", linenumber="0")) dn = "Table Column Header" st = self.stylesManager.styles.getStyle(dn) if st is None: st = add_style(name=dn, family="paragraph",parentstylename="Table Contents") st.addElement(ParagraphProperties(numberlines="false", linenumber="0")) st.addElement(TextProperties(fontweight="bold")) dn = "Bold Text" st = self.stylesManager.styles.getStyle(dn) if st is None: st = add_style(name=dn, family="text",parentstylename="Default") #~ st = add_style(name=dn, family="text") st.addElement(TextProperties(fontweight="bold")) if False: dn = "L1" st = self.stylesManager.styles.getStyle(dn) if st is None: st = ListStyle(name=dn) doc.styles.addElement(st) p = ListLevelProperties(listlevelpositionandspacemode="label-alignment") st.addElement(p) #~ label-followed-by="listtab" text:list-tab-stop-position="1.27cm" fo:text-indent="-0.635cm" fo:margin-left="1.27cm"/> p.addElement(ListLevelLabelAlignment(labelfollowedby="listtab", listtabstopposition="1.27cm", textindent="-0.635cm", marginleft="1.27cm" )) self.my_styles.append(st) #~ list_style = add_style(name=dn, family="list") bullet = text.ListLevelStyleBullet(level=1,stylename="Bullet_20_Symbols",bulletchar=u"•") #~ bullet = text.ListLevelStyleBullet(level=1,stylename="Bullet_20_Symbols",bulletchar=u"*") #~ <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" text:bullet-char="•"> st.addElement(bullet) # create some automatic styles def add_style(**kw): st = Style(**kw) doc.automaticstyles.addElement(st) self.my_automaticstyles.append(st) return st cell_style = add_style(name="Lino Cell Style",family="table-cell") cell_style.addElement(TableCellProperties( paddingleft="1mm",paddingright="1mm", paddingtop="1mm",paddingbottom="0.5mm", border="0.002cm solid #000000")) header_row_style = add_style(name="Lino Header Row",family="table-row",parentstylename=cell_style) header_row_style.addElement(TableRowProperties(backgroundcolor="#eeeeee")) total_row_style = add_style(name="Lino Total Row",family="table-row",parentstylename=cell_style) total_row_style.addElement(TableRowProperties(backgroundcolor="#ffffff")) table = Table(name=table_style_name,stylename=table_style_name) table_columns = TableColumns() table.addElement(table_columns) table_header_rows = TableHeaderRows() table.addElement(table_header_rows) table_rows = TableRows() table.addElement(table_rows) # create table columns and automatic table-column styles for i,fld in enumerate(columns): #~ print 20120415, repr(fld.name) name = str(ar.actor)+"."+fld.name cs = add_style(name=name, family="table-column") if use_relative_widths: cs.addElement(TableColumnProperties(relcolumnwidth=width_specs[i])) else: cs.addElement(TableColumnProperties(columnwidth=width_specs[i])) #~ cs.addElement(TableColumnProperties(useoptimalcolumnwidth='true')) #~ k = cs.getAttribute('name') #~ renderer.stylesManager.styles[k] = toxml(e) #~ doc.automaticstyles.addElement(cs) #~ self.my_automaticstyles.append(cs) table_columns.addElement(TableColumn(stylename=name)) from lino.ui import elems def fldstyle(fld): #~ if isinstance(fld,ext_store.VirtStoreField): #~ fld = fld.delegate if isinstance(fld,elems.NumberFieldElement): return "Number Cell" return "Table Contents" def value2cell(ar,i,fld,val,style_name,tc): #~ text = html2odt.html2odt(fld.value2html(ar,val)) params = dict() #~ if isinstance(fld,ext_store.BooleanStoreField): #~ params.update(text=fld.value2html(ar,val)) #~ else: #~ params.update(text=fld.format_value(ar,val)) #~ params.update(text=fld.format_value(ar,val)) txt = fld.value2html(ar,val) p = text.P(stylename=style_name) html2odf(txt,p) try: tc.addElement(p) except Exception as e: logger.warning("20120614 addElement %s %s %r : %s", i, fld, val, e) #~ print 20120614, i, fld, val, e #~ yield P(stylename=tablecontents,text=text) # create header row #~ hr = TableRow(stylename=HEADER_ROW_STYLE_NAME) hr = TableRow(stylename=header_row_style) table_header_rows.addElement(hr) for h in headers: #~ for fld in fields: #~ tc = TableCell(stylename=CELL_STYLE_NAME) tc = TableCell(stylename=cell_style) tc.addElement(text.P( stylename="Table Column Header", #~ text=force_unicode(fld.field.verbose_name or fld.name))) text=force_unicode(h))) hr.addElement(tc) sums = [fld.zero for fld in columns] for row in ar.data_iterator: #~ for grp in ar.group_headers(row): #~ raise NotImplementedError() tr = TableRow() has_numeric_value = False for i,fld in enumerate(columns): #~ tc = TableCell(stylename=CELL_STYLE_NAME) tc = TableCell(stylename=cell_style) #~ if fld.field is not None: v = fld.field._lino_atomizer.full_value_from_object(row,ar) stylename = fldstyle(fld) if v is None: tc.addElement(text.P(stylename=stylename,text='')) else: value2cell(ar,i,fld,v,stylename,tc) nv = fld.value2num(v) if nv != 0: sums[i] += nv has_numeric_value = True #~ sums[i] += fld.value2num(v) tr.addElement(tc) if has_numeric_value or not ar.actor.hide_zero_rows: table_rows.addElement(tr) if not ar.actor.hide_sums: if sums != [fld.zero for fld in columns]: tr = TableRow(stylename=total_row_style) table_rows.addElement(tr) for i,fld in enumerate(columns): tc = TableCell(stylename=cell_style) stylename = fldstyle(fld) p = text.P(stylename=stylename) e = fld.format_sum(ar,sums,i) html2odf(e,p) tc.addElement(p) #~ if len(txt) != 0: #~ msg = "html2odf() returned " #~ logger.warning(msg) #~ txt = tuple(html2odf(fld.format_sum(ar,sums,i),p)) #~ assert len(txt) == 1 #~ tc.addElement(text.P(stylename=stylename,text=txt[0])) tr.addElement(tc) doc.text.addElement(table) return toxml(table)
def 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