Ejemplo n.º 1
0
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 ()
Ejemplo n.º 2
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"'''))
Ejemplo n.º 3
0
 def __init__(self):
     self.book = OpenDocumentSpreadsheet()
     self.book.automaticstyles.addElement(TITLE_STYLE)
     self.book.automaticstyles.addElement(HEADER_STYLE)
     self.book.automaticstyles.addElement(HIGHLIGHT_STYLE)
     self.sheet = Table(name=self.title)
     self.book.spreadsheet.addElement(self.sheet)
Ejemplo n.º 4
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("TEST.odt")
        self.saved = True
        d = load("TEST.odt")
        result = d.contentxml()
        self.assertNotEqual(-1, result.find(u'''<number:percentage-style'''))
        self.assertNotEqual(-1, result.find(u'''style:data-style-name="N11"'''))
        self.assertNotEqual(-1, result.find(u'''style:name="pourcent"'''))
Ejemplo 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]
Ejemplo n.º 6
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]
Ejemplo n.º 7
0
def main(month):

    # Start the table, and describe the columns
    table = Table(name="jixiao")
    table.addElement(TableColumn(numbercolumnsrepeated=16, stylename=widthwide))

    # glue start
    get_udata()
    get_3m_data(month)
    get_total_creat()
    header(table)
    all_odt(table, 0)
    all_odt(table, 1)
    footer(table)
    # glue end

    doc.spreadsheet.addElement(table)

    # save to file

    if not os.path.isdir("output"):
        os.makedirs("output")

    # output/2015-06
    ods_path = "output/%s" % month
    doc.save(ods_path, True)  # odfpy auto add file prefix *.ods
Ejemplo n.º 8
0
def create_odf_table(name, data):
    """
    returns an odf table object that has been added a first row containing
    the columns' title

    """
    table = Table(name=name)

    # we need to add columns. The columns itself do not contain the data
    # though. So, we add them only for the first row.
    for c in range(len(data[0])):
        # add table columns
        col = TableColumn(numbercolumnsrepeated=1, stylename="wCol0")
        table.addElement(col)

    for i, item in enumerate(data):

        # the first row contains the table heading, which is colored
        # differently from the rest of the table. Additionally,
        style = "bgrOrange" if i == 0 else None

        logger.debug("row content:%s", item)
        tr = create_odf_table_row(item, style)
        table.addElement(tr)

    return table
Ejemplo n.º 9
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()
Ejemplo n.º 10
0
 def pictable(num):
     table = Table()
     table.addElement(TableColumn(numbercolumnsrepeated=2,stylename=tablestyle))
     for word in data[num].params.keys():
         if word in transword and data[num].params[word] != None:
             tr = TableRow()
             tr.addElement(ttb(tabletext, transword[word]))
             tr.addElement(ttb(tabletext, data[num].params[word]))
             table.addElement(tr)
     return table
Ejemplo n.º 11
0
class ODSSheetWriter(SheetWriter):
    """
    ODS sheet writer
    """

    def set_sheet_name(self, name):
        """initialize the native table"""
        self._native_sheet = Table(name=name)

    def set_size(self, size):
        """not used in this class but used in ods3"""
        pass

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

    def close(self):
        """
        This call writes file

        """
        self._native_book.spreadsheet.addElement(self._native_sheet)
Ejemplo n.º 12
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)
Ejemplo n.º 13
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
Ejemplo n.º 14
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)
Ejemplo n.º 15
0
def inittable(textdoc):
 # 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)
 widewidth = Style(name="co1", family="table-column")
 widewidth.addElement(TableColumnProperties(columnwidth="9", breakbefore="auto"))
 textdoc.automaticstyles.addElement(widewidth)
 textdoc.styles.addElement(widewidth)
 table = Table( name='test' )
 table.addElement(TableColumn(stylename=widewidth, defaultcellstylename="ce1"))
 return table,tablecontents,textdoc
Ejemplo n.º 16
0
class ODSSheetWriter(SheetWriter):
    """
    ODS sheet writer
    """
    def set_sheet_name(self, name):
        """initialize the native table"""
        self._native_sheet = Table(name=name)

    def set_size(self, size):
        """not used in this class but used in ods3"""
        pass

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

    def close(self):
        """
        This call writes file

        """
        self._native_book.spreadsheet.addElement(self._native_sheet)
Ejemplo n.º 17
0
    def render(self):
        table = Table(name=self._name)
        table.addElement(TableColumn(stylename=self._calc.style_co1))

        for row in range(self._rows):
            tr = TableRow()
            table.addElement(tr)

            for col in range(self._cols):
                try:
                    tc = self._cells[(row, col)]
                except KeyError:
                    tc = TableCell()
                tr.addElement(tc)
        return table
Ejemplo n.º 18
0
    def createTargetFormat(self, metricValues: Dict[str, List[int]],
                           metricLabels: List[str]) -> bytes:
        textdoc = OpenDocumentSpreadsheet()
        tablecontents = Style(name="Table Contents", family="paragraph")
        tablecontents.addElement(
            ParagraphProperties(numberlines="false", linenumber="0"))
        tablecontents.addElement(TextProperties(fontweight="bold"))
        textdoc.styles.addElement(tablecontents)

        table = Table(name="Java Metrics")

        tr = self.newRow(table)
        for metricLabel in metricLabels:
            self.addElementToRow(metricLabel, "string", tr, tablecontents)

        for methodName in metricValues.keys():
            tr = self.newRow(table)
            self.addElementToRow(methodName, "string", tr, tablecontents)

            for metricValue in metricValues[methodName]:
                self.addElementToRow(str(metricValue), "float", tr,
                                     tablecontents)

        textdoc.spreadsheet.addElement(table)

        stringOutput = BytesIO()
        textdoc.write(stringOutput)
        return stringOutput.getvalue()
Ejemplo n.º 19
0
    def createFinalReportTargetFormat(self, finalReport: List[list]) -> bytes:
        textdoc = OpenDocumentSpreadsheet()
        tablecontents = Style(name="Table Contents", family="paragraph")
        tablecontents.addElement(
            ParagraphProperties(numberlines="false", linenumber="0"))
        tablecontents.addElement(TextProperties(fontweight="bold"))
        textdoc.styles.addElement(tablecontents)

        table = Table(name="Java Metrics")

        tr = self.newRow(table)
        for columnLabels in finalReport[0]:
            self.addElementToRow(columnLabels, "string", tr, tablecontents)

        for row in finalReport[1:]:
            tr = self.newRow(table)
            self.addElementToRow(row[0], "string", tr, tablecontents)
            self.addElementToRow(row[1], "string", tr, tablecontents)

            for element in row[2:]:
                self.addElementToRow(str(element), "float", tr, tablecontents)

        textdoc.spreadsheet.addElement(table)

        stringOutput = BytesIO()
        textdoc.write(stringOutput)
        return stringOutput.getvalue()
Ejemplo n.º 20
0
 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)
Ejemplo 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)
Ejemplo n.º 22
0
	def generate(self, target_file):
		""" List each requirement and it's details """

		repo_dir = get_repo_dir()

		rt = RequirementTree()
		rt.load_repository(repo_dir)

		template_file = 'project-estimation-template.ods'

		try:
			template_file_path = os.path.join('templates', template_file)
			template_file_path = os.path.join(repo_dir, template_file_path)
			ods = odf.opendocument.load(template_file_path)
		except Exception as e:
			report_error(1, 'Unable to open template "%s"' % template_file_path)

		if rt._pretty_name:
			ods.meta.addElement(odf.dc.Title(text=rt._pretty_name))
		else:
			ods.meta.addElement(odf.dc.Title(text='[Set name in project.conf]'))

		# Add data sheet
		data_tbl = Table(name="Data")

		# Data header row
		data_tbl.addElement(self.make_row(['Name', 'Hours', 'Cost']))

		items = 1
		for item in rt.get_tree_items():
			if isinstance(item, Requirement) or isinstance(item, RequirementPackage):
				items += 1
				data_tbl.addElement(self.make_row([item._pretty_name, item.estimated_effort, item.estimated_cost]))

		calc_tbl = ods.spreadsheet.firstChild
		calc_2nd_row = calc_tbl.childNodes[3]

		calc_tbl.insertBefore(self.make_row(['Total estimated hours', '=SUM(Data.B2:Data.B%s' % items]), calc_2nd_row)
		calc_tbl.insertBefore(self.make_row(['Total estimated cost', '=SUM(Data.C2:Data.C%s' % items]), calc_2nd_row)

		ods.spreadsheet.addElement(data_tbl)

		try:
			ods.save(target_file, True)
		except:
			report_error(1, 'Unable to write to "%s", is file open?' % target_file)
Ejemplo n.º 23
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)
Ejemplo n.º 24
0
def inittable(textdoc):
    # 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)
    widewidth = Style(name="co1", family="table-column")
    widewidth.addElement(
        TableColumnProperties(columnwidth="9", breakbefore="auto"))
    textdoc.automaticstyles.addElement(widewidth)
    textdoc.styles.addElement(widewidth)
    table = Table(name='test')
    table.addElement(
        TableColumn(stylename=widewidth, defaultcellstylename="ce1"))
    return table, tablecontents, textdoc
Ejemplo n.º 25
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 = ''
Ejemplo n.º 26
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
Ejemplo n.º 27
0
class ODSSheetWriter(SheetWriter):
    """
    ODS sheet writer
    """
    def set_sheet_name(self, name):
        self.native_sheet = Table(name=name)

    def set_size(self, size):
        pass

    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_row(self, array):
        """
        write a row into the file
        """
        tr = TableRow()
        self.native_sheet.addElement(tr)
        for cell in array:
            self.write_cell(tr, cell)

    def close(self):
        """
        This call writes file

        """
        self.native_book.spreadsheet.addElement(self.native_sheet)
Ejemplo n.º 28
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
Ejemplo n.º 29
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)
Ejemplo n.º 30
0
def create_odf_table(name, data):
    """
    returns an odf table object that has been added a first row containing
    the columns' title

    """
    table = Table(name=name)

    # we need to add columns. The columns itself do not contain the data
    # though. So, we add them only for the first row.
    for c in range(len(data[0])):
        # add table columns
        col = TableColumn(numbercolumnsrepeated=1, stylename="wCol0")
        table.addElement(col)

    for i, item in enumerate(data):

        # the first row contains the table heading, which is colored
        # differently from the rest of the table. Additionally,
        style = "bgrOrange" if i == 0 else None

        logger.debug("row content:%s", item)
        tr = create_odf_table_row(item, style)
        table.addElement(tr)

    return table
Ejemplo n.º 31
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()
    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)
Ejemplo n.º 33
0
class ODSSheetWriter(SheetWriter):
    """
    ODS sheet writer
    """
    def set_sheet_name(self, name):
        self.native_sheet = Table(name=name)

    def set_size(self, size):
        pass

    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 write_row(self, array):
        """
        write a row into the file
        """
        tr = TableRow()
        self.native_sheet.addElement(tr)
        for x in array:
            self.write_cell(tr, x)

    def close(self):
        """
        This call writes file

        """
        self.native_book.spreadsheet.addElement(self.native_sheet)
Ejemplo n.º 34
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])
class Sheet(object):
    def __init__(self, name):
        self._table = Table(name=name)
        self._rows = {}

    def create_row(self, name, **kwargs):
        """Create an empty row to manually insert cells"""
        self._rows[name] = Row(**kwargs)
        self._table.addElement(self._rows[name]._row)

        return self._rows[name]

    def write_row(self, name, cells, row_styles={}, cell_styles={}):
        """Create a new row and populate it with the given cells"""
        row = self.create_row(name, **row_styles)
        row.write_cells(cells, **cell_styles)

    def get_row(self, name):
        return self._rows[name]

    def create_column(self, **kwargs):
        column = TableColumn(**kwargs)

        self._table.addElement(column)

    def read_cell(self, x, y):
        try:
            cell = self._table.getElementsByType(TableRow)[y].childNodes[x]
        except IndexError:
            return ''

        result = []

        for element in cell.childNodes:
            result.append("".join([v.data for v in element.childNodes]))

        return "\n".join(result)
Ejemplo n.º 36
0
 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
Ejemplo n.º 37
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
Ejemplo n.º 38
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
Ejemplo n.º 39
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
Ejemplo n.º 40
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)
Ejemplo n.º 41
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
Ejemplo n.º 42
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
Ejemplo n.º 43
0
Archivo: views.py Proyecto: zxdvd/snoek
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
Ejemplo n.º 44
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)
Ejemplo n.º 45
0
class ODFTable:
    PWENC = "utf-8"
    
    def __init__(self, outputFilename, orderType='p'):
        self.outputFilename = outputFilename
        self.orderType = orderType
        self.table = None
        self.finding = 1
        
        self.initializeDocument()

    def initializeDocument( self ):
      
	self.textdoc = OpenDocumentText()
        
	# Create a style for the table content. One we can modify
	# later in the word processor.
	self.tablecontents = Style(name="Table Contents", family="paragraph")
	self.tablecontents.addElement(ParagraphProperties(numberlines="false", linenumber="0"))
	self.textdoc.styles.addElement(self.tablecontents)
        
        
        # ----------------- define a few styles --------------------
        
        # a Bold style
        self.BoldStyle = Style(name="Bold", family="paragraph")
        self.BoldProp = TextProperties(fontweight="bold")
        self.BoldStyle.addElement(self.BoldProp)
        self.textdoc.automaticstyles.addElement(self.BoldStyle)
        
        # for Critical findings
        self.CriticalStyle = Style(name="Critical Findings", family="paragraph")
        self.CriticalStyleProp = TextProperties(fontweight="bold", color="#FF0000")
        self.CriticalStyle.addElement(self.CriticalStyleProp)
        self.textdoc.automaticstyles.addElement(self.CriticalStyle)
        
        # for High findings
        self.HighStyle = Style(name="High Findings", family="paragraph")
        self.HighStyleProp = TextProperties(fontweight="bold", color="#FF2400")
        self.HighStyle.addElement(self.HighStyleProp)
        self.textdoc.automaticstyles.addElement(self.HighStyle)        
        
        # for Moderate findings
        self.ModerateStyle = Style(name="Moderate Findings", family="paragraph")
        self.ModerateStyleProp = TextProperties(fontweight="bold", color="#FF7F00")
        self.ModerateStyle.addElement(self.ModerateStyleProp)
        self.textdoc.automaticstyles.addElement(self.ModerateStyle)        
        
        # for Low findings
        self.LowStyle = Style(name="Low Findings", family="paragraph")
        self.LowStyleProp = TextProperties(fontweight="bold", color="#007FFF")
        self.LowStyle.addElement(self.LowStyleProp)
        self.textdoc.automaticstyles.addElement(self.LowStyle)        

        # for 'None' or 'Info' or 'Note' findings
        self.NoteStyle = Style(name="Note Findings", family="paragraph")
        self.NoteStyleProp = TextProperties(fontweight="bold")
        self.NoteStyle.addElement(self.NoteStyleProp)
        self.textdoc.automaticstyles.addElement(self.NoteStyle)                

        # nessus plugins can give widely inconsistent ratings: serious/high, medium/moderate, info/note/none...
        self.riskFactorsDict = {
           'critical':self.CriticalStyle,
           'high':self.HighStyle,
           'serious':self.HighStyle,
           'medium':self.ModerateStyle,
           'moderate':self.ModerateStyle,
           'low':self.LowStyle,
           'info':self.NoteStyle,
           'note':self.NoteStyle,
           'none':self.NoteStyle
           }
        
	# Create automatic styles for the column widths.
	# We want two different widths, one in inches, the other one in metric.
	# ODF Standard section 15.9.1
	widthshort = Style(name="Wshort", family="table-column")
	widthshort.addElement(TableColumnProperties(columnwidth="1.7cm"))
	self.textdoc.automaticstyles.addElement(widthshort)

	widthwide = Style(name="Wwide", family="table-column")
	widthwide.addElement(TableColumnProperties(columnwidth="1.5in"))
	self.textdoc.automaticstyles.addElement(widthwide)
        
        
        
        # hard-code columns styles, per column
	widthwide = Style(name="Wwide", family="table-column")
	widthwide.addElement(TableColumnProperties(columnwidth="1.5in"))
	self.textdoc.automaticstyles.addElement(widthwide)        
        

	# Start the table and describe the columns
	self.table = Table()
	if self.orderType=='p':
	    self.table.addElement(TableColumn(numbercolumnsrepeated=7,stylename=widthwide))

        # populate columns with headers...
        tr = TableRow()
        self.table.addElement(tr)
        
        # declare necessary vars
        tc1 = TableCell(); tc2 = TableCell(); tc3 = TableCell(); tc4 = TableCell(); tc5 = TableCell(); tc6 = TableCell(); tc7 = TableCell();
        addElem = lambda cell, text, s=self: cell.addElement(ODFParagraph(stylename=self.BoldStyle, text=unicode(text, ODFTable.PWENC)))


        # Add Column 1: Finding Number
        addElem(tc1, 'Finding Number')
        tr.addElement(tc1)
        
        # Add Column 2: Vulnerability Name
        addElem(tc2, 'Vulnerability Name')
        tr.addElement(tc2)
        
        # Add Column 3: NIST 800-53 Mapping
        addElem(tc3, '800-53 Mapping')
        tr.addElement(tc3)
        
        # Add Column 4: Description
        addElem(tc4, 'Description')
        tr.addElement(tc4)
        
        # Add Column 5: Recommendation
        addElem(tc5, 'Recommendation')
        tr.addElement(tc5)
        
        # Add Column 6: CVE
        addElem(tc6, 'CVE')
        tr.addElement(tc6)
        
        # Add Column 6: Hosts Affected
        addElem(tc7, 'IP Address (Sample of hosts effected)')
        tr.addElement(tc7)        

        
    # Print a single entry
    def printEntry( self, options, result, _ipList=[], count=1 ):

        if _ipList==[]: ipList=[result.getIP()]
        else: ipList = ipsort(_ipList)
    
        # print header

        tr = TableRow()
        self.table.addElement(tr)
        '''
        Finding Number
        Vulnerability Name
        800-53 Mapping
        Description
        Recommendation
        CVE
        IP Address (Sample of hosts effected)
        '''        


        tc1 = TableCell(); tc2 = TableCell(); tc3 = TableCell(); tc4 = TableCell(); tc5 = TableCell(); tc6 = TableCell(); tc7 = TableCell();
        addElem = lambda cell, text, s=self: cell.addElement(ODFParagraph(stylename=s.tablecontents, text=text.encode(ODFTable.PWENC)))
        
        
        riskFactor = result.getRiskFactor()

        # ---- Populate Column 1: Finding Number ----
        
        addElem(tc1, '') 
        addElem(tc1, str(count))
        tr.addElement(tc1)
        
        # increment the findings count (goes into first column)
        # self.finding+=1

        # ---- Populate Column 2: Vulnerability Description (prepended with port# and service name) ----
        
        #  grab the portnum
        portString='\n%s/%s (%s)' % (result.getPort(), result.getProtocol().upper(), result.getServiceName().upper())
        
        #  grab the first sentence of the synopsis (this forms a concise one-line description). 
        vulnerabilityString = unicode(result.getSynopsis().split('.',1)[0].replace('\\n', "\n") + '.')
        po = result.getPluginOutput()
        if po is not '':
            pluginOutput = '\n\nPlugin output:\n\n' + po
        else:
            pluginOutput = ''
        
        tc2.addElement( ODFParagraph(stylename=self.BoldStyle, text=(vulnerabilityString.decode("iso8859-8") + '\n' + portString).encode(ODFTable.PWENC)))
        tr.addElement(tc2)
        
        # ---- Populate Column 3:  NIST 800-53 Mapping ----
        tc3.addElement( ODFParagraph(stylename=self.BoldStyle, text=''.encode(ODFTable.PWENC)) )
        tr.addElement(tc3)

        # ---- Populate Column 4: Implication ----
        descString = ''.join(result.getDescription().replace('\\n', '\n')) # + pluginOutput.replace('\\n', '\n'))
        addElem(tc4, descString.strip() )
        tc4.addElement( ODFParagraph(stylename=self.BoldStyle, text="\n\n   RISK RATING:  ".encode(ODFTable.PWENC)))
        tc4.addElement( ODFParagraph(stylename=self.riskFactorsDict[riskFactor], text=riskFactor.encode(ODFTable.PWENC)))
        tr.addElement(tc4)
        
        # Populate  Column 5: Recomendation
        _recText = result.getRecommendation().replace('\\n', '\n')
        seeAlsoText = result.getSeeAlso().replace('\\n', '\n')
        solutionText = result.getSolution()
        if seeAlsoText is not '' or solutionText is not '':  
            recText = '\n'.join([_recText, '\n\n See also: ', seeAlsoText])
        else:
            recText = _recText
        addElem(tc5, recText)
        tr.addElement(tc5)
        
        # Column 6: CVE
        _cveText = result.getCVE()
        addElem(tc6, _cveText.encode("utf-8"))
        tr.addElement(tc6)

        # Populate Column 7: IP Address (Sample of hosts affected)
        addElem(tc7, '\n'.join(ipsort(uniq(ipList))))
        tr.addElement(tc7)

        
    def saveAndClose( self ):
        self.textdoc.text.addElement( self.table )
        self.textdoc.save(self.outputFilename)
Ejemplo n.º 46
0
    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)
Ejemplo n.º 47
0
p.addElement(s)
p.addText(' is ')
link = A(type="simple",href="http://www.flickr.com/services/api", 
text="http://www.flickr.com/services/api")
p.addElement(link)

textdoc.text.addElement(p)

# add the table
"""
<table:table-column table:number-columns-repeated="3"/>
"""

textdoc.text.addElement(H(outlinelevel=1,text='A Table (Heading 1)'))

table = Table(name="Table 1")

table.addElement(TableColumn(numbercolumnsrepeated="3"))

# first row
tr = TableRow()
table.addElement(tr)
tc = TableCell(valuetype="string")
tc.addElement(P(text='Website'))
tr.addElement(tc)
tc = TableCell(valuetype="string")
tc.addElement(P(text='Description'))
tr.addElement(tc)
tc = TableCell(valuetype="string")
tc.addElement(P(text='URL'))
tr.addElement(tc)
Ejemplo n.º 48
0
    def initializeDocument( self ):
      
	self.textdoc = OpenDocumentText()
        
	# Create a style for the table content. One we can modify
	# later in the word processor.
	self.tablecontents = Style(name="Table Contents", family="paragraph")
	self.tablecontents.addElement(ParagraphProperties(numberlines="false", linenumber="0"))
	self.textdoc.styles.addElement(self.tablecontents)
        
        
        # ----------------- define a few styles --------------------
        
        # a Bold style
        self.BoldStyle = Style(name="Bold", family="paragraph")
        self.BoldProp = TextProperties(fontweight="bold")
        self.BoldStyle.addElement(self.BoldProp)
        self.textdoc.automaticstyles.addElement(self.BoldStyle)
        
        # for Critical findings
        self.CriticalStyle = Style(name="Critical Findings", family="paragraph")
        self.CriticalStyleProp = TextProperties(fontweight="bold", color="#FF0000")
        self.CriticalStyle.addElement(self.CriticalStyleProp)
        self.textdoc.automaticstyles.addElement(self.CriticalStyle)
        
        # for High findings
        self.HighStyle = Style(name="High Findings", family="paragraph")
        self.HighStyleProp = TextProperties(fontweight="bold", color="#FF2400")
        self.HighStyle.addElement(self.HighStyleProp)
        self.textdoc.automaticstyles.addElement(self.HighStyle)        
        
        # for Moderate findings
        self.ModerateStyle = Style(name="Moderate Findings", family="paragraph")
        self.ModerateStyleProp = TextProperties(fontweight="bold", color="#FF7F00")
        self.ModerateStyle.addElement(self.ModerateStyleProp)
        self.textdoc.automaticstyles.addElement(self.ModerateStyle)        
        
        # for Low findings
        self.LowStyle = Style(name="Low Findings", family="paragraph")
        self.LowStyleProp = TextProperties(fontweight="bold", color="#007FFF")
        self.LowStyle.addElement(self.LowStyleProp)
        self.textdoc.automaticstyles.addElement(self.LowStyle)        

        # for 'None' or 'Info' or 'Note' findings
        self.NoteStyle = Style(name="Note Findings", family="paragraph")
        self.NoteStyleProp = TextProperties(fontweight="bold")
        self.NoteStyle.addElement(self.NoteStyleProp)
        self.textdoc.automaticstyles.addElement(self.NoteStyle)                

        # nessus plugins can give widely inconsistent ratings: serious/high, medium/moderate, info/note/none...
        self.riskFactorsDict = {
           'critical':self.CriticalStyle,
           'high':self.HighStyle,
           'serious':self.HighStyle,
           'medium':self.ModerateStyle,
           'moderate':self.ModerateStyle,
           'low':self.LowStyle,
           'info':self.NoteStyle,
           'note':self.NoteStyle,
           'none':self.NoteStyle
           }
        
	# Create automatic styles for the column widths.
	# We want two different widths, one in inches, the other one in metric.
	# ODF Standard section 15.9.1
	widthshort = Style(name="Wshort", family="table-column")
	widthshort.addElement(TableColumnProperties(columnwidth="1.7cm"))
	self.textdoc.automaticstyles.addElement(widthshort)

	widthwide = Style(name="Wwide", family="table-column")
	widthwide.addElement(TableColumnProperties(columnwidth="1.5in"))
	self.textdoc.automaticstyles.addElement(widthwide)
        
        
        
        # hard-code columns styles, per column
	widthwide = Style(name="Wwide", family="table-column")
	widthwide.addElement(TableColumnProperties(columnwidth="1.5in"))
	self.textdoc.automaticstyles.addElement(widthwide)        
        

	# Start the table and describe the columns
	self.table = Table()
	if self.orderType=='p':
	    self.table.addElement(TableColumn(numbercolumnsrepeated=7,stylename=widthwide))

        # populate columns with headers...
        tr = TableRow()
        self.table.addElement(tr)
        
        # declare necessary vars
        tc1 = TableCell(); tc2 = TableCell(); tc3 = TableCell(); tc4 = TableCell(); tc5 = TableCell(); tc6 = TableCell(); tc7 = TableCell();
        addElem = lambda cell, text, s=self: cell.addElement(ODFParagraph(stylename=self.BoldStyle, text=unicode(text, ODFTable.PWENC)))


        # Add Column 1: Finding Number
        addElem(tc1, 'Finding Number')
        tr.addElement(tc1)
        
        # Add Column 2: Vulnerability Name
        addElem(tc2, 'Vulnerability Name')
        tr.addElement(tc2)
        
        # Add Column 3: NIST 800-53 Mapping
        addElem(tc3, '800-53 Mapping')
        tr.addElement(tc3)
        
        # Add Column 4: Description
        addElem(tc4, 'Description')
        tr.addElement(tc4)
        
        # Add Column 5: Recommendation
        addElem(tc5, 'Recommendation')
        tr.addElement(tc5)
        
        # Add Column 6: CVE
        addElem(tc6, 'CVE')
        tr.addElement(tc6)
        
        # Add Column 6: Hosts Affected
        addElem(tc7, 'IP Address (Sample of hosts effected)')
        tr.addElement(tc7)        
Ejemplo n.º 49
0
# Text
h=H(outlinelevel=1, stylename=h1style, text="Factura")
doc.text.addElement(h)
p = P(stylename=boldstyle)
boldpart = Span(stylename=boldstyle, text=" NEXUSCOMPUTER,S.L.")

# con line-break creamos saltos de linea y con P() vacio igualmente es un salto de linea
insertar_linea(1,doc)
p.addElement(boldpart)
doc.text.addElement(p)

# ++++ TABLAS ++++

# TABLA de informacion NEXUS
table = Table()
table.addElement(TableColumn(numbercolumnsrepeated=2,stylename=widthshort))

# Abrimos fichero donde esta la informacion que vamos a insertar en la tabla
f = open('/home/dani/workspace/openinvo_aux/Programa_facturacion/archivo')

# partimos la linea segun nos encontremos punto y coma  annadimos la linea a la tabla
for line in f:
    izquierda = 0
    tr = TableRow()
    tar = line.strip().split(";")
    table.addElement(tr)
    #por cada valor de la linea partida creamos una celda e insertamos el valor 
    for val in tar: 
        if (izquierda == 0):             
            tc = TableCell()
Ejemplo n.º 50
0
    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)
Ejemplo n.º 51
0
ns2.addElement(Text(text=u"-"))
ns2.addElement(CurrencySymbol(language="en", country="AU", text=u"$"))
ns2.addElement(Number(decimalplaces="2", minintegerdigits="1",
                      grouping="true"))
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")
Ejemplo n.º 52
0
  def save(self, filename, i_max = None, j_max = None):
    ''' save table in ods format '''

    if not i_max: i_max = self.table.i_max
    if not j_max: j_max = self.table.j_max

    # update cells text
    self.table.updateTable(i_max, j_max)

    # create new odf spreadsheet
    odfdoc = OpenDocumentSpreadsheet()

    # set direction style
    rtl = Style(name = "dir", family = "table")
    if self.table.direction == 'rtl':
      rtl.addElement(TableProperties(writingmode="rl-tb"))
    odfdoc.automaticstyles.addElement(rtl)

    # create the table
    table = Table(name = "sheet 1", stylename = 'dir')
    
    # default style
    ts = Style(name = "ts", family = "table-cell")
    ts.addElement(TextProperties(fontfamily = SodsCell().font_family, fontsize = SodsCell().font_size))
    odfdoc.styles.addElement(ts)

    # create columns
    for j in range(1, j_max):
      colname = "col" + str(j)
      c = self.table.getCellAt(0, j)
      width = c.column_width
      cs = Style(name = colname, family = "table-column")
      cs.addElement(TableColumnProperties(columnwidth = width, breakbefore = "auto"))
      odfdoc.automaticstyles.addElement(cs)

      table.addElement(TableColumn(stylename = colname, defaultcellstylename = "ts"))

    # make sure values are up to date
    # loop and update the cells value
    for i in range(1, i_max):
      # create new ods row
      tr = TableRow()
      table.addElement(tr)

      # create default data styles for dates and numbers
      ncs = NumberStyle(name="ncs")
      ncs.addElement(Number(decimalplaces="2", minintegerdigits="1", grouping="true"))
      odfdoc.styles.addElement(ncs)

      ncs2 = NumberStyle(name="ncs2")
      ncs2.addElement(Number(decimalplaces="0", minintegerdigits="1", grouping="false"))
      odfdoc.styles.addElement(ncs2)

      dcs = DateStyle(name="dcs")
      dcs.addElement(Year(style='long'))
      dcs.addElement(Text(text = u'-'))
      dcs.addElement(Month(style='long'))
      dcs.addElement(Text(text = u'-'))
      dcs.addElement(Day(style='long'))
      odfdoc.styles.addElement(dcs)

      for j in range(1, j_max):
        # update the cell text and condition
        cell = self.table.encodeColName(j) + str(i)
        c = self.table.getCellAt(i, j)

        # chose datastylename
        if c.value_type == 'date':
          datastylename = "dcs"
        else:
          if c.format == "":
            datastylename = "ncs2"
          if c.format == "#,##0.00":
            datastylename = "ncs"

        # get cell style id
        if (c.condition):
          style_id = (datastylename + c.color + c.font_size + c.font_family + 
            c.background_color + c.border_top + c.border_bottom + 
            c.border_left + c.border_right + 
            c.condition_color + c.condition_background_color)
        else:
          style_id = (datastylename + c.color + c.font_size + c.font_family + 
            c.background_color + c.border_top + c.border_bottom + 
            c.border_left + c.border_right)

        # set ods style
        style_name = self.getStyle(c, cell, datastylename, style_id, odfdoc)

        # create new ods cell
        if (c.formula and c.formula[0] == '=' and c.formula[:4] != '=uni'):
          if self.table.isFloat(c.value):
            tc = TableCell(valuetype = c.value_type, 
              formula = c.formula, value = float(c.value), stylename = style_name)
          else:
            tc = TableCell(valuetype = c.value_type, 
              formula = c.formula, 
              value = 0, stylename = style_name)
        elif (c.value_type == 'date'):
          tc = TableCell(valuetype = c.value_type, 
            datevalue = c.date_value, stylename = style_name)
        elif (c.value_type == 'float') and self.table.isFloat(c.value):
          tc = TableCell(valuetype = c.value_type, 
            value = float(c.value), stylename = style_name)
        else:
          tc = TableCell(valuetype = 'string', stylename = style_name)

        # set ods text
        tc.addElement(P(text = unicode(escape(c.text), 'utf-8')))
        
        tr.addElement(tc)

    odfdoc.spreadsheet.addElement(table)
    odfdoc.save(filename)
Ejemplo n.º 53
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
Ejemplo n.º 54
0
def doit(args) :
    logfile = args.logger
    if args.report: logfile.loglevel = args.report

    try:
        root = ET.parse(args.input).getroot()
    except:
        logfile.log("Error parsing FTML input", "S")

    if args.font:                   # font(s) specified on command line
        fontlist = getfonts( args.font, logfile )
    else:                           # get font spec from FTML fontsrc element
        fontlist = getfonts( [root.find("./head/fontsrc").text], logfile, False )
        #fontlist = getfonts( [fs.text for fs in root.findall("./head/fontsrc")], False ) ### would allow multiple fontsrc elements
    numfonts = len(fontlist)
    if numfonts == 0:
        logfile.log("No font(s) specified", "S")
    if numfonts > 1:
        formattedfontnum = ["{0:02d}".format(n) for n in range(numfonts)]
    else:
        formattedfontnum = [""]
    logfile.log("Font(s) specified:", "V")
    for n, (fontname, bold, italic, embeddedfont) in enumerate(fontlist):
        logfile.log(" " + formattedfontnum[n] + " " + fontname + BoldItalic(bold, italic) + " " + str(embeddedfont), "V")

    # get optional fontscale; compute pointsize as int(12*fontscale/100). If result xx is not 12, then add "fo:font-size=xxpt" in Px styles
    pointsize = 12
    fontscaleel = root.find("./head/fontscale")
    if fontscaleel != None:
        fontscale = fontscaleel.text
        try:
            pointsize = int(int(fontscale)*12/100)
        except ValueError:
            # any problem leaves pointsize 12
            logfile.log("Problem with fontscale value; defaulting to 12 point", "W")

    # Get FTML styles and generate LO writer styles
    # P2 is paragraph style for string element when no features specified
    # each Px (for P3...) corresponds to an FTML style, which specifies lang or feats or both
    # if numfonts > 1, two-digit font number is appended to make an LO writer style for each FTML style + font combo
    # When LO writer style is used with attribute rtl="True", "R" appended to style name
    LOstyles = {}
    ftmlstyles = {}
    Pstylenum = 2
    LOstyles["P2"] = ("", None, None)
    ftmlstyles[0] = "P2"
    for s in root.findall("./head/styles/style"):
        Pstylenum += 1
        Pnum = "P" + str(Pstylenum)
        featstring = ""
        if s.get('feats'):
            featstring = parsefeats(s.get('feats'))
        langname = None
        countryname = None
        lang = s.get('lang')
        if lang != None:
            x = re.match(langcode, lang)
            langname = x.group('langname')
            countryname = x.group('countryname')
        # FTML <test> element @stylename attribute references this <style> element @name attribute
        ftmlstyles[s.get('name')] = Pnum
        LOstyles[Pnum] = (featstring, langname, countryname)

    # create LOwriter file and construct styles for tables, column widths, etc.
    LOdoc = OpenDocumentText()
    init(LOdoc, numfonts)
    # Initialize sequence counters
    sds = SequenceDecls()
    sd = sds.addElement(SequenceDecl(displayoutlinelevel = '0', name = 'Illustration'))
    sd = sds.addElement(SequenceDecl(displayoutlinelevel = '0', name = 'Table'))
    sd = sds.addElement(SequenceDecl(displayoutlinelevel = '0', name = 'Text'))
    sd = sds.addElement(SequenceDecl(displayoutlinelevel = '0', name = 'Drawing'))
    LOdoc.text.addElement(sds)

    # Create Px style for each (featstring, langname, countryname) tuple in LOstyles
    # and for each font (if >1 font, append to Px style name a two-digit number corresponding to the font in fontlist)
    # and (if at least one rtl attribute) suffix of nothing or "R"
    # At the same time, collect info for creating FontFace elements (and any embedded fonts)
    suffixlist = ["", "R"] if root.find(".//test/[@rtl='True']") != None else [""]
    fontfaces = {}
    for p in sorted(LOstyles, key = lambda x : int(x[1:])):  # key = lambda x : int(x[1:]) corrects sort order
        featstring, langname, countryname = LOstyles[p]
        for n, (fontname, bold, italic, embeddedfont) in enumerate(fontlist): # embeddedfont = None if no embedding needed
            fontnum = formattedfontnum[n]
            # Collect fontface info: need one for each font family + feature combination
            # Put embedded font in list only under fontname with empty featstring
            if (fontname, featstring) not in fontfaces:
                fontfaces[ (fontname, featstring) ] = []
            if embeddedfont:
                if (fontname, "") not in fontfaces:
                    fontfaces[ (fontname, "") ] = []
                if embeddedfont not in fontfaces[ (fontname, "") ]:
                    fontfaces[ (fontname, "") ].append(embeddedfont)
            # Generate paragraph styles
            for s in suffixlist:
                pstyle = Style(name=p+fontnum+s, family="paragraph")
                if s == "R":
                    pstyle.addElement(ParagraphProperties(textalign="end", justifysingleword="false", writingmode="rl-tb"))
                pstyledic = {}
                pstyledic['fontnamecomplex'] = \
                pstyledic['fontnameasian'] =\
                pstyledic['fontname'] = fontname + featstring
                pstyledic['fontsizecomplex'] = \
                pstyledic['fontsizeasian'] = \
                pstyledic['fontsize'] = str(pointsize) + "pt"
                if bold:
                    pstyledic['fontweightcomplex'] = \
                    pstyledic['fontweightasian'] = \
                    pstyledic['fontweight'] = 'bold'
                if italic:
                    pstyledic['fontstylecomplex'] = \
                    pstyledic['fontstyleasian'] = \
                    pstyledic['fontstyle'] = 'italic'
                if langname != None:
                    pstyledic['languagecomplex'] = \
                    pstyledic['languageasian'] = \
                    pstyledic['language'] = langname
                if countryname != None:
                    pstyledic['countrycomplex'] = \
                    pstyledic['countryasian'] = \
                    pstyledic['country'] = countryname
                pstyle.addElement(TextProperties(attributes=pstyledic))
#                LOdoc.styles.addElement(pstyle)    ### tried this, but when saving the generated odt, LO changed them to automatic styles
                LOdoc.automaticstyles.addElement(pstyle)

    fontstoembed = []
    for fontname, featstring in sorted(fontfaces):  ### Or find a way to keep order of <style> elements from original FTML?
        ff = FontFace(name=fontname + featstring, fontfamily=fontname + featstring, fontpitch="variable")
        LOdoc.fontfacedecls.addElement(ff)
        if fontfaces[ (fontname, featstring) ]:     # embedding needed for this combination
            for fontfile in fontfaces[ (fontname, featstring) ]:
                fontstoembed.append(fontfile)       # make list for embedding
                ffsrc = FontFaceSrc()
                ffuri = FontFaceUri( **{'href': "Fonts/" + os.path.basename(fontfile), 'type': "simple"} )
                ffformat = FontFaceFormat( **{'string': 'truetype'} )
                ff.addElement(ffsrc)
                ffsrc.addElement(ffuri)
                ffuri.addElement(ffformat)

    basename = "Table1.B"
    colorcount = 0
    colordic = {} # record color #rrggbb as key and "Table1.Bx" as stylename (where x is current color count)
    tablenum = 0

    # get title and comment and use as title and subtitle
    titleel = root.find("./head/title")
    if titleel != None:
        LOdoc.text.addElement(H(outlinelevel=1, stylename="Title", text=titleel.text))
    commentel = root.find("./head/comment")
    if commentel != None:
        LOdoc.text.addElement(P(stylename="Subtitle", text=commentel.text))

    # Each testgroup element begins a new table
    for tg in root.findall("./testgroup"):
        # insert label attribute of testgroup element as subtitle
        tglabel = tg.get('label')
        if tglabel != None:
            LOdoc.text.addElement(H(outlinelevel=1, stylename="Subtitle", text=tglabel))

        # insert text from comment subelement of testgroup element
        tgcommentel = tg.find("./comment")
        if tgcommentel != None:
            #print("commentel found")
            LOdoc.text.addElement(P(text=tgcommentel.text))

        tgbg = tg.get('background') # background attribute of testgroup element
        tablenum += 1
        table = Table(name="Table" + str(tablenum), stylename="Table1")
        table.addElement(TableColumn(stylename="Table1.A"))
        for n in range(numfonts):
            table.addElement(TableColumn(stylename="Table1.B"))
        table.addElement(TableColumn(stylename="Table1.A"))
        table.addElement(TableColumn(stylename="Table1.D"))
        for t in tg.findall("./test"):                # Each test element begins a new row
            # stuff to start the row
            labeltext = t.get('label')
            stylename = t.get('stylename')
            stringel = t.find('./string')
            commentel = t.find('./comment')
            rtlsuffix = "R" if t.get('rtl') == 'True' else ""
            comment = commentel.text if commentel != None else None
            colBstyle = "Table1.A1"
            tbg = t.get('background')   # get background attribute of test group (if one exists)
            if tbg == None: tbg = tgbg
            if tbg != None:             # if background attribute for test element (or background attribute for testgroup element)
                if tbg not in colordic: # if color not found in color dic, create new style
                    colorcount += 1
                    newname = basename + str(colorcount)
                    colordic[tbg] = newname
                    tb1style = Style(name=newname, family="table-cell")
                    tb1style.addElement(TableCellProperties(attributes={'padding':"0.0382in", 'border':"0.05pt solid #000000", 'backgroundcolor':tbg}))
                    LOdoc.automaticstyles.addElement(tb1style)
                colBstyle = colordic[tbg]

            row = TableRow()
            table.addElement(row)
            # fill cells
            # column A (label)
            cell = TableCell(stylename="Table1.A1", valuetype="string")
            if labeltext:
                cell.addElement(P(stylename="Table_20_Contents", text = labeltext))
            row.addElement(cell)

            # column B (string)
            for n in range(numfonts):
                Pnum = ftmlstyles[stylename] if stylename != None else "P2"
                Pnum = Pnum + formattedfontnum[n] + rtlsuffix
                ### not clear if any of the following can be moved outside loop and reused
                cell = TableCell(stylename=colBstyle, valuetype="string")
                par = P(stylename=Pnum)
                if len(stringel) == 0: # no <em> subelements
                    par.addText(re.sub(backu, hextounichr, stringel.text))
                else:   # handle <em> subelement(s)
                    if stringel.text != None:
                        par.addElement(Span(stylename="T1", text = re.sub(backu, hextounichr, stringel.text)))
                    for e in stringel.findall("em"):
                        if e.text != None:
                            par.addText(re.sub(backu, hextounichr, e.text))
                        if e.tail != None:
                            par.addElement(Span(stylename="T1", text = re.sub(backu, hextounichr, e.tail)))
                cell.addElement(par)
                row.addElement(cell)

            # column C (comment)
            cell = TableCell(stylename="Table1.A1", valuetype="string")
            if comment:
                cell.addElement(P(stylename="Table_20_Contents", text = comment))
            row.addElement(cell)

            # column D (stylename)
            cell = TableCell(stylename="Table1.A1", valuetype="string")
            if comment:
                cell.addElement(P(stylename="Table_20_Contents", text = stylename))
            row.addElement(cell)
        LOdoc.text.addElement(table)

    LOdoc.text.addElement(P(stylename="Subtitle", text="")) # Empty paragraph to end ### necessary?

    try:
        if fontstoembed: logfile.log("Embedding fonts in document", "V")
        for f in fontstoembed:
            LOdoc._extra.append(
                OpaqueObject(filename = "Fonts/" + os.path.basename(f),
                    mediatype = "application/x-font-ttf",      ### should be "application/font-woff" or "/font-woff2" for WOFF fonts, "/font-opentype" for ttf
                    content = io.open(f, "rb").read() ))
        ci = ConfigItem(**{'name':'EmbedFonts', 'type': 'boolean'}) ### (name = 'EmbedFonts', type = 'boolean')
        ci.addText('true')
        cis=ConfigItemSet(**{'name':'ooo:configuration-settings'})  ### (name = 'ooo:configuration-settings')
        cis.addElement(ci)
        LOdoc.settings.addElement(cis)
    except:
        logfile.log("Error embedding fonts in document", "E")
    logfile.log("Writing output file: " + args.output, "P")
    LOdoc.save(unicode(args.output))
    return
Ejemplo n.º 55
0
 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]
Ejemplo n.º 56
0
#tablecontents.addElement(TextProperties(fontweight="bold"))
textdoc.styles.addElement(tablecontents)

# Create automatic styles for the column widths.
# We want two different widths, one in inches, the other one in metric.
# ODF Standard section 15.9.1
widthshort = Style(name="Wshort", family="table-column")
widthshort.addElement(TableColumnProperties(columnwidth="1.7cm"))
textdoc.automaticstyles.addElement(widthshort)

widthwide = Style(name="Wwide", family="table-column")
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:
Ejemplo n.º 57
0
def odsResponse(inscriptions, noninscrits):
    """
    fabrique un objet de type HttpResponse qui comporte un tableur au format
    ODS, avec les exportations d'une "barrette" d'AP.    
    @param inscriptions un objet issu de Inscription.objects.all()
    @param noninscrits une liste d'Etudiants
    @return un objet de type HttpResponse
    """
    response = HttpResponse(content_type='application/vnd.oasis.opendocument.spreadsheet')
    now=timezone.now()
    filename="aperho-{}.ods".format(now.strftime("%Y%m%d-%H%M"))
    response['Content-Disposition'] = 'attachment; filename={}'.format(filename)
    doc = OpenDocumentSpreadsheet()
    # Create a style for the table content. One we can modify
    # later in the word processor.
    tablecontents = Style(name="Table Contents", family="paragraph")
    tablecontents.addElement(ParagraphProperties(numberlines="false", linenumber="0"))
    tablecontents.addElement(TextProperties(fontweight="bold"))
    doc.styles.addElement(tablecontents)

    # Create automatic styles for the column widths.
    # We want two different widths, one in inches, the other one in metric.
    # ODF Standard section 15.9.1
    widthshort = Style(name="Wshort", family="table-column")
    widthshort.addElement(TableColumnProperties(columnwidth="1.7cm"))
    doc.automaticstyles.addElement(widthshort)

    widthwide = Style(name="Wwide", family="table-column")
    widthwide.addElement(TableColumnProperties(columnwidth="1.5in"))
    doc.automaticstyles.addElement(widthwide)

    # Start the table, and describe the columns
    table = Table(name="Inscriptions")
    table.addElement(TableColumn(numbercolumnsrepeated=3,stylename=widthwide))
    tr = TableRow()
    table.addElement(tr)
    for title in ['id', 'Eleve_nom', 'Eleve_prenom', 'Eleve_classe', 'Professeur', 'Salle', 'Heure', 'Duree', 'Public_designe', 'Resume','Detail','Autres']:
        tc = TableCell()
        tr.addElement(tc)
        p = P(stylename=tablecontents,text=title)
        tc.addElement(p)
    for i in inscriptions:
        tr = TableRow()
        table.addElement(tr)
        for val in [i.pk, i.etudiant.nom, i.etudiant.prenom, i.etudiant.classe, i.cours.enseignant.nom, i.cours.enseignant.salle, i.cours.horaire, i.cours.formation.duree, i.cours.formation.public_designe, i.cours.formation.titre, i.cours.formation.contenu]:
            tc = TableCell()
            tr.addElement(tc)
            p = P(stylename=tablecontents,text=str(val))
            tc.addElement(p)
        ## write something in the last column (Autres)
        tc = TableCell()
        tr.addElement(tc)
        p = P(stylename=tablecontents,text=rdvOrientation(i))
        tc.addElement(p)
    for e in noninscrits:
        tr = TableRow()
        table.addElement(tr)
        for val in [0, e.nom, e.prenom, e.classe, '', '', '', '', '', '', '','']:
            tc = TableCell()
            tr.addElement(tc)
            p = P(stylename=tablecontents,text=str(val))
            tc.addElement(p)
    doc.spreadsheet.addElement(table)
    output=BytesIO()
    doc.save(output)
    response.write(output.getvalue())
    return response
Ejemplo n.º 58
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
Ejemplo n.º 59
0
def odtResponse(eci, horaires, noninscrits, cci=None):
    """
    fabrique un objet de type HttpResponse qui comporte un tableur au format
    ODT, avec les exportations d'une "barrette" d'AP.
    @param eci un dictionnaire de dictionnaires enseignant => cours => inscriptions
    @param horaires les horaires existant dans la "barrette"
    @param noninscrits une liste d'Etudiants
    @param cci dictionnaire cop -> coursOrientation -> inscriptionOrientations
    @return un objet de type HttpResponse
    """
    ## détermine d'abord s'il y a des séances d'orientation, pour la dernière
    ## ouverture en date. yaCop est un booléen vrai si les COP interviennent.
    yaCop=len(Orientation.objects.filter(
        ouverture=Ouverture.objects.last()
    )) > 0
    response = HttpResponse(content_type='application/vnd.oasis.opendocument.text')
    now=timezone.now()
    filename="aperho-{}.odt".format(now.strftime("%Y%m%d-%H%M"))
    response['Content-Disposition'] = 'attachment; filename={}'.format(filename)

    textdoc = OpenDocumentText()

    tablecontents = Style(name="Table Contents", family="paragraph")
    tablecontents.addElement(ParagraphProperties(numberlines="false", linenumber="0"))
    tablecontents.addElement(TextProperties(fontweight="bold"))
    textdoc.styles.addElement(tablecontents)

    w=[] # styles de largeurs de colonnes
    w1 = Style(name="Wwide1", family="table-column")
    w1.addElement(TableColumnProperties(columnwidth="0.5in"))
    textdoc.automaticstyles.addElement(w1)
    w.append(w1)
    w2 = Style(name="Wwide2", family="table-column")
    w2.addElement(TableColumnProperties(columnwidth="2in"))
    textdoc.automaticstyles.addElement(w2)
    w.append(w2)
    w3 = Style(name="Wwide3", family="table-column")
    w3.addElement(TableColumnProperties(columnwidth="1.5in"))
    textdoc.automaticstyles.addElement(w3)
    w.append(w3)
    w4 = Style(name="Wwide4", family="table-column")
    w4.addElement(TableColumnProperties(columnwidth="1in"))
    textdoc.automaticstyles.addElement(w4)
    w.append(w4)
    w5 = Style(name="Wwide5", family="table-column")
    w5.addElement(TableColumnProperties(columnwidth="4in"))
    textdoc.automaticstyles.addElement(w5)
    w.append(w5)

    withbreak = Style(name="WithBreak", parentstylename="Standard", family="paragraph")
    withbreak.addElement(ParagraphProperties(breakbefore="page"))
    textdoc.automaticstyles.addElement(withbreak)

    for e,ci in eci.items():
        # e est un enseignant, ci est un dictionnaire
        p = P(stylename=withbreak,text="") # saut de page manuel
        textdoc.text.addElement(p)
        for c,inscriptions in ci.items():
            titre="{} {} ({}, {}h, {})".format(c.horaire, c.enseignant.nom, c.enseignant.salle, c.formation.duree, c.formation.titre)
            textdoc.text.addElement(H(text=titre, outlinelevel=1))
            ### on début un tableau n°, Nom, prénom, classe pour les élèves
            table = Table()
            nbCol=4
            if yaCop:
                nbCol=5
            for i in range(nbCol):
                table.addElement(TableColumn(stylename=w[i]))
            textdoc.text.addElement(table)
            n=1
            tr = TableRow()
            table.addElement(tr)
            colTitres=("n°","Nom","Prénom","Classe")
            if yaCop:
                colTitres=("n°","Nom","Prénom","Classe", "Séance COP")
            for val in colTitres:
                tc = TableCell()
                tr.addElement(tc)
                p = P(stylename=tablecontents,text=str(val))
                tc.addElement(p)
            for i in inscriptions:
                tr = TableRow()
                table.addElement(tr)
                for val in [n, i.etudiant.nom, i.etudiant.prenom, i.etudiant.classe]:
                    tc = TableCell()
                    tr.addElement(tc)
                    p = P(text=val)
                    tc.addElement(p)
                if yaCop:
                    tc = TableCell()
                    tr.addElement(tc)
                    p = P(text=rdvOrientation(i))
                    tc.addElement(p)                    
                n+=1
        #après chaque enseignant, on passe une page.

    p = P(stylename=withbreak,text="") # saut de page manuel
    textdoc.text.addElement(p)
    titre="Élèves non encore inscrits"
    textdoc.text.addElement(H(text=titre, outlinelevel=1))
    ni=list(noninscrits)
    ni.sort(key=lambda e: (e.classe, e.nom, e.prenom))
    for e in ni:
        ligne="{} {} {}".format(e.classe, e.nom, e.prenom)
        textdoc.text.addElement(P(text=ligne))

    if cci:
        for cop, ci in cci.items():
            titre="Conseillère d'orientation : {}".format(cop.nom)
            for cours, inscr in ci.items():
                p = P(stylename=withbreak,text="") # saut de page manuel
                textdoc.text.addElement(p)
                textdoc.text.addElement(H(text=titre, outlinelevel=1))
                titre2="{} {} avec {}".format(localtime(cours.debut).strftime("%d/%m/%Y %H%M"), cours.choice, cours.prof)
                textdoc.text.addElement(H(text=titre2, outlinelevel=2))
                ### on débute un tableau n°, Nom, prénom, classe pour les élèves
                table = Table()
                nbCol=4
                for i in range(nbCol):
                    table.addElement(TableColumn(stylename=w[i]))
                textdoc.text.addElement(table)
                tr = TableRow()
                table.addElement(tr)
                colTitres=("n°","Nom","Prénom","Classe")
                for val in colTitres:
                    tc = TableCell()
                    tr.addElement(tc)
                    p = P(stylename=tablecontents,text=str(val))
                    tc.addElement(p)
                ### compteur d'élèves au minimum ...
                n=1
                ### puis on ajoute une ligne par inscription
                for i in inscr:
                    tr = TableRow()
                    table.addElement(tr)
                    for val in [n, i.etudiant.nom, i.etudiant.prenom, i.etudiant.classe]:
                        tc = TableCell()
                        tr.addElement(tc)
                        p = P(text=val)
                        tc.addElement(p)
                    n+=1
        
    output=BytesIO()
    textdoc.save(output)
    response.write(output.getvalue())
    return response