Exemplo n.º 1
0
 def _getRowByIndex(self, idx):
     assert idx > 0, f"Wrong row index: {idx}"
     rown = 0
     for row in self.__sheet.getElementsByType(TableRow):
         n = int(row.getAttribute('numberrowsrepeated') or 1)
         if rown + n > idx:
             if idx - rown == 1:
                 # we are in the target row, just remove the repeated attribute
                 # and insert a new row with repeated decreased by 1
                 row.removeAttribute('numberrowsrepeated')
                 newrow = TableRow(stylename=row.getAttribute('stylename'), numberrowsrepeated=n - 1)
                 self.__sheet.insertBefore(newrow, row.nextSibling)
                 return Row(idx, row)
             # we are in a previous row, just remove the repeated, and add two new rows,
             # one being the target row and another with repeated decreased by two
             row.removeAttribute('numberrowsrepeated')
             nextSibling = row.nextSibling
             newrow = TableRow(stylename=row.getAttribute('stylename'))
             self.__sheet.insertBefore(newrow, nextSibling)
             if n > 2:
                 newnewrow = TableRow(stylename=row.getAttribute('stylename'))
                 if n > 3:
                     newnewrow.setAttribute('numberrowsrepeated', n - 2)
                 self.__sheet.insertBefore(newnewrow, nextSibling)
             return Row(idx, newrow)
         if rown + n == idx:
             return Row(idx, row)
         rown += n
     raise ValueError(f"Error retrieving row {idx}")
Exemplo n.º 2
0
 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)
Exemplo n.º 3
0
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
Exemplo n.º 4
0
 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)
Exemplo n.º 5
0
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)
Exemplo n.º 7
0
 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)
Exemplo n.º 8
0
    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"'''))
Exemplo n.º 9
0
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()
Exemplo n.º 10
0
 def write_row(self, array):
     """
     write a row into the file
     """
     row = TableRow()
     self._native_sheet.addElement(row)
     for cell in array:
         self.write_cell(row, cell)
Exemplo n.º 11
0
 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)
Exemplo n.º 12
0
    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])
Exemplo n.º 13
0
    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
Exemplo n.º 14
0
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()
Exemplo n.º 15
0
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
Exemplo n.º 16
0
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
Exemplo n.º 17
0
    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)
Exemplo n.º 18
0
 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)
Exemplo n.º 19
0
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
Exemplo n.º 20
0
 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)
Exemplo n.º 21
0
    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)
Exemplo n.º 22
0
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 = ''
Exemplo n.º 23
0
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
Exemplo n.º 24
0
    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
Exemplo n.º 25
0
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
Exemplo n.º 26
0
 def as_table(self):
     """Convert to a odf.table.Table object"""
     t = Table(name=self.name)
     # Find out max row and col
     maxcol = max(col for col, row in self._contents.keys())
     maxrow = max(row for col, row in self._contents.keys())
     # Add column styles
     for c in range(0, maxcol + 1):
         s = self._columnstyles.get(c, None)
         if s:
             t.addElement(TableColumn(stylename=s))
         else:
             t.addElement(TableColumn())
     for row in range(0, maxrow + 1):
         tr = TableRow()
         t.addElement(tr)
         for col in range(0, maxcol + 1):
             cell = self._contents.get((col, row), None)
             if cell:
                 tr.addElement(cell)
             else:
                 tr.addElement(TableCell())
     return t
Exemplo n.º 27
0
    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
Exemplo n.º 28
0
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
Exemplo n.º 29
0
    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
Exemplo n.º 30
0
ns2.addElement(Map(condition="value()>=0", applystylename="positive-AUD"))
textdoc.styles.addElement(ns2)

# 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)