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 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 _writeodsitem(self, col, value): """Uses col and value to make entry in ods file (using self.currentrow)""" # column numbering starts at 1 for spreadsheet column A curcol = 0 ### restarts at beginning of row for each entry targetcol = col r = self.currentrow for c in r.childNodes: if c.tagName != 'table:table-cell': continue repeatedcols = c.getAttribute('numbercolumnsrepeated') repcount = int(repeatedcols) if repeatedcols else 1 if curcol + repcount >= targetcol: break curcol += repcount else: pass ### got to end of row without finding desired column; add more cells? or report bad col? ### doesn't preserve background color (see Time Zones for example) countbefore = targetcol - curcol - 1 countafter = curcol + repcount - targetcol if countbefore > 0: c1 = TableCell() c1.setAttribute('numbercolumnsrepeated', str(countbefore)) c.setAttribute('numbercolumnsrepeated', str(countafter + 1)) x = r.insertBefore(c1, c) if countafter > 0: c.setAttribute('numbercolumnsrepeated', '1') c2 = TableCell() c2.setAttribute('numbercolumnsrepeated', str(countafter)) if c == r.lastChild: x = r.appendChild(c2) else: x = r.insertBefore(c2, c.nextSibling) if c.hasChildNodes(): ### perhaps should test that child is text:p and its child is Text c.firstChild.firstChild.data = value else: c.addElement(P(text=value))
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 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 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 _write_cells( self, cells: list[ExcelCell], sheet_name: str | None = None, startrow: int = 0, startcol: int = 0, freeze_panes: tuple[int, int] | None = 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.book.spreadsheet.addElement(wks) if validate_freeze_panes(freeze_panes): freeze_panes = cast(Tuple[int, int], freeze_panes) 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 if len(rows) > 0: for row_nr in range(max(rows.keys()) + 1): wks.addElement(rows[row_nr])
def _make_table_cell(self, cell) -> tuple[object, 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): # Fast formatting value = val.isoformat() # Slow but locale-dependent pvalue = val.strftime("%c") return ( pvalue, TableCell(valuetype="date", datevalue=value, attributes=attributes), ) elif isinstance(val, datetime.date): # Fast formatting value = f"{val.year}-{val.month:02d}-{val.day:02d}" # Slow but locale-dependent 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 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 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 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 _copycell(odfcell, **kwargs): kw = {} for _, attr in odfcell.attributes.keys(): attr = attr.replace('-', '') kw[attr] = odfcell.getAttribute(attr) kw.update(kwargs) return TableCell(**kw)
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 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 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 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 get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]: """ Parse an ODF Table into a list of lists """ from odf.table import ( CoveredTableCell, TableCell, TableRow, ) covered_cell_name = CoveredTableCell().qname table_cell_name = TableCell().qname cell_names = {covered_cell_name, table_cell_name} sheet_rows = sheet.getElementsByType(TableRow) empty_rows = 0 max_row_len = 0 table: List[List[Scalar]] = [] for i, sheet_row in enumerate(sheet_rows): sheet_cells = [x for x in sheet_row.childNodes if x.qname in cell_names] empty_cells = 0 table_row: List[Scalar] = [] for j, sheet_cell in enumerate(sheet_cells): if sheet_cell.qname == table_cell_name: value = self._get_cell_value(sheet_cell, convert_float) else: value = self.empty_value column_repeat = self._get_column_repeat(sheet_cell) # Queue up empty values, writing only if content succeeds them if value == self.empty_value: empty_cells += column_repeat else: table_row.extend([self.empty_value] * empty_cells) empty_cells = 0 table_row.extend([value] * column_repeat) if max_row_len < len(table_row): max_row_len = len(table_row) row_repeat = self._get_row_repeat(sheet_row) if self._is_empty_row(sheet_row): empty_rows += row_repeat else: # add blank rows to our table table.extend([[self.empty_value]] * empty_rows) empty_rows = 0 for _ in range(row_repeat): table.append(table_row) # Make our table square for row in table: if len(row) < max_row_len: row.extend([self.empty_value] * (max_row_len - len(row))) return table
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(self, attributes=None, rowspan=1, colspan=1): tc = TableCell(attributes=attributes) tc.number = self.nextcell self.nextcell += colspan tc.setAttribute('numberrowsspanned', str(rowspan)) tc.setAttribute('numbercolumnsrepeated', str(colspan)) tc.setAttribute('numbercolumnsspanned', str(colspan)) self.row.addElement(tc) return tc
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 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)
def convert_FFPtable_day(path): name = "FFPtable.day" table = Table(name=name) with open(path) as fin: line = fin.readline().split()[2:] row = TableRow() for year in line: table.addElement(TableColumn()) cell = TableCell(valuetype="float", value=year) row.addElement(cell) table.addElement(row) for line in fin.readlines(): line = line.split()[2:] row = TableRow() for item in line: cell = TableCell(valuetype="float", value=item) row.addElement(cell) table.addElement(row) return table
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 _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 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 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 convert_FFPtable_USO(path): name = "FFPtable.uso" table = Table(name=name) with open(path) as fin: for i in range(2): table.addElement(TableColumn()) for line in fin.readlines(): line = line.split() row = TableRow() for item in line: cell = TableCell(valuetype="float", value=item) row.addElement(cell) table.addElement(row) return table
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 _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