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 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 sample(): textdoc = OpenDocumentText() # Styles s = textdoc.styles h1style = Style(name="Heading 1", family="paragraph") h1style.addElement( TextProperties(attributes={ 'fontsize': "24pt", 'fontweight': "bold" })) s.addElement(h1style) # An automatic style boldstyle = Style(name="Bold", family="text") boldprop = TextProperties(fontweight="bold") boldstyle.addElement(boldprop) textdoc.automaticstyles.addElement(boldstyle) # Text h = H(outlinelevel=1, stylename=h1style, text="My first texta") textdoc.text.addElement(h) p = P(text="Hello world. ") boldpart = Span(stylename=boldstyle, text="This part is bold. ") p.addElement(boldpart) p.addText("This is after bold.") quotStyle = Style(name="Quotations") marginaliaStyle = Style(name="Marginalia") # p2 = P(text="2nd par. ", stylename=textBodyStyle) p3 = P(text="3rd par. ", stylename=quotStyle) textdoc.text.addElement(p) textdoc.text.addElement(p2) textdoc.text.addElement(p3) a = textdoc.save("myfirstdocument.odt")
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 make_parent_id(self, dict): """cree la page texte à partir des champs csv le texte est lu dans home/.refnumtool.d/text_extract_tuteur.yaml :param dict: dictionnaire des champs du tuteur issus du csv (elycee) """ self.addParagraph("Remise Identifiant ENT: Responsable", "heading1") table_content = [["Responsable", "Élève", "Classe"],\ [dict["nom"]+" "+dict["prenom"],\ dict["nom enfant"]+ " " + dict["prenom enfant"],\ dict["classe"]]] # self.classe self.addTable(table_content, "tablecontents", [ {"numbercolumnsrepeated": 1, "stylename": "column1"}, {"numbercolumnsrepeated": 1, "stylename": "column2"}, {"numbercolumnsrepeated": 1, "stylename": "column3"} ]) self.addParagraph("", "normal") self.addParagraph(self.msg["annonce"][0], "normal") self.addParagraph(self.msg["annonce"][1], "normal") self.addParagraph(self.msg["annonce"][2], "normal") self.addParagraph(self.msg["annonce"][3], "normal") stylename = getattr(self, "gras", None) p = P(stylename=stylename, text="votre identifiant: "+dict["login"]) #p.addElement(Tab()) q = P(stylename=stylename, text="mot de passe provisoire: "+dict["mot de passe"]) self.document.text.addElement(p) self.document.text.addElement(q) self.addParagraph("", "normal") self.addParagraph(self.msg["annonce"][4], "normal") self.addList(self.msg["actions"], "normal") self.addParagraph(self.msg["annonce"][5], "normal")
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 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 render_subblock(self, doc, num, problems, text, show_solution): base = (num - 1) * 10 + 1 doc.text.addElement( H(outlinelevel=1, stylename=self.h1style, text="{} Teil {}".format(text, num))) for i, p in enumerate(problems): p = P(text="{}) {}".format(base + i, p.render(show_solution))) doc.text.addElement(p) doc.text.addElement(P())
def test_list(self): textdoc = OpenDocumentText() s = textdoc.styles listStyle = easyliststyle.styleFromString(u'bullet1', bulletListSpec, u',', u'0.6cm', easyliststyle.SHOW_ONE_LEVEL) s.addElement(listStyle) result = textdoc.stylesxml() self.assertNotEqual(-1, result.find(u'''style:name="bullet1"''')) self.assertNotEqual(-1, result.find(u'''text:bullet-char="*"''')) self.assertNotEqual(-1, result.find(u'''text:level="1"''')) self.assertNotEqual(-1, result.find(u'''style:list-level-properties''')) #<text:list-style style:name="bullet1" style:display-name="bullet1"> #<text:list-level-style-bullet text:bullet-char="*" text:level="1"> #<style:list-level-properties text:min-label-width="0.6cm" text:space-before="0.6cm"/> #</text:list-level-style-bullet> #<text:list-level-style-bullet text:bullet-char=">" text:level="2"> #<style:list-level-properties text:min-label-width="0.6cm" text:space-before="1.2cm"/> #</text:list-level-style-bullet> #<text:list-level-style-bullet text:bullet-char="#" text:level="3"> #<style:list-level-properties text:min-label-width="0.6cm" text:space-before="1.8cm"/> #</text:list-level-style-bullet> #<text:list-level-style-bullet text:bullet-char="%" text:level="4"> #<style:list-level-properties text:min-label-width="0.6cm" text:space-before="2.4cm"/> listElement = self.createList(itemList, u'>', u'bullet1') textdoc.text.addElement(listElement) para = P(text="-----------------------") textdoc.text.addElement(para) listStyle = easyliststyle.styleFromList('num1', numberListSpecArray, '0.25in', easyliststyle.SHOW_ALL_LEVELS) s.addElement(listStyle) listElement = self.createList(itemList, '>', 'num1') textdoc.text.addElement(listElement) para = P(text="-----------------------") textdoc.text.addElement(para) listStyle = easyliststyle.styleFromString('mix1', mixedListSpec, '!', '0.8cm', easyliststyle.SHOW_ONE_LEVEL) s.addElement(listStyle) listElement = self.createList(itemList, '>', 'mix1') textdoc.text.addElement(listElement)
def addHeaderFooter(self,header=None,footer=None): if header or footer: mp = MasterPage(name="Standard", pagelayoutname=self.plheaderstyle) self.textdoc.masterstyles.addElement(mp) if header: h = Header() hp = P(text=header)#,stylename=self.headerstyle) h.addElement(hp) mp.addElement(h) if footer: f = Footer() fp = P(text=footer,stylename=self.footercenterstyle) f.addElement(fp) mp.addElement(f)
def __init__(self, strMode): """ Initialise highlighter: strMode = language (PYTHON, C, CPP, PHP, HTML) """ self.textdoc = OpenDocumentText() self.textdoc.fontfacedecls.addElement(self.courierfont) self.textdoc.styles.addElement(self.programliststyle) self.textdoc.styles.addElement(self.puncstyle) self.textdoc.styles.addElement(self.numberstyle) self.textdoc.styles.addElement(self.keywordstyle) self.textdoc.styles.addElement(self.variablestyle) self.textdoc.styles.addElement(self.tagstyle) self.textdoc.styles.addElement(self.attrstyle) self.textdoc.styles.addElement(self.stringstyle) self.textdoc.styles.addElement(self.commentstyle) self.textdoc.styles.addElement(self.preprocstyle) self.strSpanStyle = None self.currPara = P(stylename=self.programliststyle) self.textdoc.text.addElement(self.currPara) self.currSpan = None if strMode == 'CPP': strMode = 'C' self.strSuppressTokens = [] elif strMode == 'C': self.strSuppressTokens = ['CPPKEYWORD'] else: self.strSuppressTokens = [] self.strMode = strMode
def addText(self, data_box): text = data_box.getText() frame_style = Style(name='FrameStyle', family='graphic') debug('Angle: %s', data_box.text_data.angle) angle = data_box.text_data.angle if angle: frame_style = Style(name='FrameStyleRotated', family='graphic') x, y, width, height = data_box.getBoundsPrintSize( self.current_page_resolution) frame = Frame(stylename=frame_style, width=str(width) + 'in', height=str(height) + 'in', x=str(x) + 'in', y=str(y) + 'in', anchortype='paragraph') if angle: frame.addAttribute( 'transform', 'rotate (%s) translate (%scm %scm)' % (abs(math.radians(angle)), x, y)) self.current_page.addElement(frame) textbox = TextBox() frame.addElement(textbox) for line in text.split('\n'): textbox.addElement( P(stylename=self.__handleFrameStyle(data_box.text_data), text=line))
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 extract_highlight_odf(name): textdoc = OpenDocumentText() location = os.path.join("/tmp/pdf_highlight/", name) doc_mask = fitzopen(location) doc_text = fitzopen(location) nb_pages = doc_text.pageCount style_p = Style(name="P1", family="paragraph", parentstylename="Standard") p_prop = ParagraphProperties(textalign="justify", justifysingleword="false") style_p.addElement(p_prop) textdoc.automaticstyles.addElement(style_p) textdoc.text.addElement(P(stylename=style_p, text=f"{name}\n\n")) for i in range(nb_pages): rect, hierarchy = Page_Get_Rects(doc_mask, doc_text, name, i) if rect.shape[0] > 0: textdoc = Page_Rect_get_Text_odf(doc_text, name, i, rect, hierarchy, textdoc, style_p) text_name = name.replace(".pdf", ".odt") location_out = os.path.join("/tmp/pdf_highlight/", text_name) textdoc.save(location_out) #print('fin') return text_name, location_out
def createList(self, itemList, indentDelim, styleName): listArray = [] listItem = ListItem() level = 0 lastLevel = 0 for levCount in range(0,10): listArray.append(None) listArray[0] = List() for item in itemList: level = 0; while (level < len(item) and item[level] == indentDelim): level +=1 item = item[level:] if (level > lastLevel): # open the sub-levels for levCount in range(lastLevel+1, level+1): listArray[levCount] = List() elif (level < lastLevel): # close off the intervening lists for levCount in range(lastLevel, level, -1): listArray[levCount-1].childNodes[-1].addElement(listArray[levCount]) # now that we are at the proper level, add the item. listArray[level].setAttribute( 'stylename', styleName ); listItem = ListItem() para = P(text=item); listItem.addElement(para); listArray[level].addElement(listItem); lastLevel = level; # close off any remaining open lists for levCount in range(lastLevel, 0, -1): listArray[levCount-1].childNodes[-1].addElement(listArray[levCount]) return listArray[0]
def addList(self,elements): textList = List(stylename="L1") for element in elements: item = ListItem() item.addElement(P(text=element)) textList.addElement(item) self.textdoc.text.addElement(textList)
def moveColumn(self, sheetname, oldcolumn, newcolumn): """Replaces the column oldcolumn with newcolumn and deletes newcolumn. This function assumes: oldcolumn > newcolumn. @param sheetname: The name of the sheet to be operated on. @type sheetname: string @param oldcolumn: The column to move data from. @type oldcolumn: int @param newcolumn: The column to move data to. @type newcolumn: int """ sheets = self._doc.spreadsheet.getElementsByType(Table) for sheet in sheets: if sheet.getAttribute('name') == sheetname: rows = sheet.getElementsByType(TableRow) for row in rows: colNum = 0 cells = row.getElementsByType(TableCell) for cell in cells: if colNum == newcolumn: newcolumncell = cell pl = cell.getElementsByType(P) for p in pl: cell.removeChild(p) elif colNum == oldcolumn: pl = cell.getElementsByType(P) if len(pl) > 0: p = P() if pl[0].firstChild: p.addText( StringUtils.toUnicode( pl[0].firstChild)) newcolumncell.addElement(p) colNum += 1
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 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 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 _process_raw_document_content(self): for line in self._raw_document_content: if line.startswith("# "): new_element = H(outlinelevel=1, stylename=self._h1_style, text=line.replace("# ", "")) else: new_element = P(text=line, stylename=self._p_style) self._document.text.addElement(new_element)
def drawChart(_document, _values, \ chartWidth, chartHeight, chartType): # Create the subdocument chartdoc = OpenDocumentChart() mychart = PieChart(chartWidth, chartHeight, chartType) # These represent the data. Six rows in three columns mychart.values = _values mychart.datasourcehaslabels = "both" mychart(chartdoc) p = P() _document.add(p) # Create the frame. df = draw.Frame(width=chartWidth, height=chartHeight, anchortype="paragraph") p.addElement(df) # Here we add the subdocument to the main document. We get back a reference # to use in the href. objectloc = _document.addAsObject(chartdoc) do = draw.Object(href=objectloc) # Put the object inside the frame df.addElement(do)
def setUp(self): d = OpenDocumentText() # Styles h1style = style.Style(name=u"Heading 1", family=u"paragraph") h1style.addElement( style.TextProperties(attributes={ 'fontsize': u"24pt", 'fontweight': u"bold" })) d.styles.addElement(h1style) boldstyle = style.Style(name=u"Bold", family=u"text") boldstyle.addElement( style.TextProperties(attributes={'fontweight': u"bold"})) d.automaticstyles.addElement(boldstyle) # Text h = H(outlinelevel=1, stylename=h1style, text=u"Simple test document") d.text.addElement(h) p = P( text= u"The earth's climate has not changed many times in the course of its long history. " ) d.text.addElement(p) boldpart = Span(stylename=boldstyle, text=u"This part is bold. ") p.addElement(boldpart) p.addText(u"This is after bold.") d.save(u"TEST.odt")
def defineStyles(self): # entête s = Style(name = "Header", family ="paragraph") prop = {"numberlines":"false", "linenumber":"0"} P = ParagraphProperties(**prop) Q = TabStops() Q.addElement(TabStop(position="8.5cm", type="center")) Q.addElement(TabStop(position="17cm", type="right")) P.addElement(Q) s.addElement(P) prop2 = {"fontfamily": "Verdana", "fontweight": "bold", "fontsize": "14pt"} s.addElement(TextProperties(**prop2)) self.document.styles.addElement(s) setattr(self, "Header", s) #autres self.addParagraphStyle("heading1", "Heading 1", paragraph_properties={"breakbefore": "page", "lineheight": "24pt"}, text_properties={"fontfamily": "Verdana", "fontweight": "bold", "fontsize": "14pt"} ) self.addParagraphStyle("heading2", "Heading 2", paragraph_properties={"breakbefore": "false", "lineheight": "24pt"}, text_properties={"fontfamily": "Verdana", "fontweight": "italic", "fontsize": "14pt"} ) self.addParagraphStyle("heading3", "Heading 3", paragraph_properties={"breakbefore": "false", "lineheight": "20pt"}, text_properties={"fontfamily": "Liberation Sans", "fontweight": "bold", "fontsize": "14pt"} ) self.addParagraphStyle("normal", "Normal", paragraph_properties={"breakbefore": "false", "lineheight": "20pt"}, text_properties={"fontfamily": "Liberation Serif", "fontsize": "12pt"} ) self.addParagraphStyle("gras", "Bgr", paragraph_properties={"breakbefore": "false", "lineheight": "20pt"}, text_properties={"fontfamily": "Liberation Serif", "fontweight": "bold", "fontsize": "12pt"} ) self.addParagraphStyle("tablecontents", "Table Contents", paragraph_properties={"numberlines": "false", "linenumber": "0"} ) self.addPageLayoutStyle("mpm1", "Mpm1", \ properties={"pagewidth":"21.001cm", "pageheight": "14.801cm",\ "numformat": "1", "printorientation": "landscape",\ "margintop":"1cm", "marginbottom": "1cm", "marginleft": "1cm",\ "marginright": "1cm", "writingmode":"lr-tb"})#, "footnotemaxheight":"0cm" self.addTableColumnStyle("column1", "Left Column", properties={"columnwidth": "4cm"}) self.addTableColumnStyle("column2", "Center Column", properties={"columnwidth": "4cm"}) self.addTableColumnStyle("column3", "Right Column", properties={"columnwidth": "2cm"})
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 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 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 addList(self, content, stylename): liste = List() for e in content: p = P(stylename=stylename, text=e) i = ListItem() i.addElement(p) liste.addElement(i) self.document.text.addElement(liste)
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 __init__(self, path, maj=False, data=None): """initialisation d'un générateur odt pour les tuteurs. En haut de chaque page A5 en sortie, il créée un tableau +----------------+-----------+--------+ | Responsable | Élève | Classe | +================+===========+========+ | nom resp | nom eleve | cl | +----------------+-----------+--------+ :param str path: chemin vers le fichier des csv tuteurs :param boolean maj: mode màj ou complet :param dict data: si maj=True, il doit contenir le dictionnaire des pp et tuteurs """ self.nom = basename(path)[:-4] #nom du fichier sans extension base = dirname(path) #fallacieux en cas de màj. # .. todo:: vérifier utilité et effacer self.classe = ((self.nom).split('Tuteur_'))[-1] #vraiment lié au nom de fichier self.document = OpenDocumentText() self.defineStyles() # def du header complet head_style = getattr(self, "Header", None) p = P(stylename=head_style) mp = MasterPage(name="Standard", pagelayoutname="Mpm1") h = Header() h.addElement(p) mp.addElement(h) self.document.masterstyles.addElement(mp) #import des textes de la page odt tuteur try: from yaml import CLoader as Loader except ImportError: from yaml import Loader home = expanduser("~/.refnumtool.d") with open(join(home,"text_extract_tuteur.yaml")) as file: self.msg = load(file, Loader=Loader) if not(maj): file = open(path, "r", encoding="utf8") dialect=csv.Sniffer().sniff(file.readline()) file.seek(0) # se remettre en début de fichier reader = csv.DictReader(file, dialect=dialect) for d in reader: self.make_parent_id(d) file.close() self.save(join(base, "ENT_id_Tuteur_"+self.classe+".odt")) else: # cas d'une màj #for pp in data.values(): # superflu, génération par classe pour les tuteurs if "Tuteur" in data: # test superflu en principe for d in data["Tuteur"]: self.make_parent_id(d) self.save(join(base, "ENT_id_Tuteur_"+data["elycee"]+"_"+time.strftime("%d%m%Y")+".odt"))