コード例 #1
0
ファイル: testdatastyles.py プロジェクト: wahlmzr/odfpy
    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"'''))
コード例 #2
0
# Create a style for the table content. One we can modify
# later in the spreadsheet.
tablecontents = Style(name="Large number", family="table-cell")
tablecontents.addElement(TextProperties(fontfamily="Arial", fontsize="15pt"))
textdoc.styles.addElement(tablecontents)

# Create automatic styles for the column widths.
widewidth = Style(name="co1", family="table-column")
widewidth.addElement(
    TableColumnProperties(columnwidth="2.8cm", breakbefore="auto"))
textdoc.automaticstyles.addElement(widewidth)

# Create the styles for $AUD format currency values
ns1 = CurrencyStyle(name="positive-AUD", volatile="true")
ns1.addElement(CurrencySymbol(language="en", country="AU", text=u"$"))
ns1.addElement(Number(decimalplaces="2", minintegerdigits="1",
                      grouping="true"))
textdoc.styles.addElement(ns1)

# Create the main style.
ns2 = CurrencyStyle(name="main-AUD")
ns2.addElement(TextProperties(color="#ff0000"))
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",
コード例 #3
0
ファイル: sodsods.py プロジェクト: rschach1/simpleodspy
	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 = '-'))
			dcs.addElement(Month(style='long'))
			dcs.addElement(Text(text = '-'))
			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 = str(escape(c.text), 'utf-8')))
				
				tr.addElement(tc)

		odfdoc.spreadsheet.addElement(table)
		odfdoc.save(filename)
コード例 #4
0
ファイル: resultats.py プロジェクト: pykol/pykhollet
def classe_resultats_odf(request, resultats):
    response = HttpResponse(
        content_type='application/vnd.oasis.opendocument.spreadsheet')
    response[
        'Content-Disposition'] = 'attachment; filename="resultats_{}.ods"'.format(
            resultats['classe'])

    ods = OpenDocumentSpreadsheet()

    # Style numérique pour les notes
    style_number_note = NumberStyle(name="Note")
    ods.styles.addElement(style_number_note)
    Number(parent=style_number_note, minintegerdigits=1, decimalplaces=2)
    style_note = Style(datastylename=style_number_note,
                       parent=ods.styles,
                       name="Note",
                       family='table-cell')

    # Style pour le rang
    style_number_rang = NumberStyle(name="Rang", parent=ods.styles)
    Number(parent=style_number_rang, minintegerdigits=1, decimalplaces=0)
    style_rang = Style(datastylename=style_number_rang,
                       parent=ods.styles,
                       name="Rang",
                       family='table-column')

    for matiere, ens_resultats in resultats['enseignements'].items():
        table = Table(name="{} - {}".format(resultats['classe'], matiere),
                      parent=ods.spreadsheet)

        # Création des colonnes
        table.addElement(TableColumn())  # Étudiant
        table.addElement(TableColumn())  # Moyenne
        table.addElement(TableColumn(stylename=style_rang))  # Rang
        for _ in range(len(resultats['semaines'])):
            table.addElement(TableColumn())

        # Ligne d'en-tête
        th = TableHeaderRows(parent=table)
        tr = TableRow(parent=th)
        P(parent=TableCell(parent=tr, valuetype='string'), text="Étudiant")
        P(parent=TableCell(parent=tr, valuetype='string'), text="Moyenne")
        P(parent=TableCell(parent=tr, valuetype='string'), text="Rang")
        for semaine in resultats['semaines']:
            P(parent=TableCell(parent=tr, valuetype='string'),
              text=semaine.numero)

        # Ligne pour chaque étudiant
        for etudiant, etu_resultats in ens_resultats['etudiants'].items():
            tr = TableRow(parent=table)

            # Nom de l'étudiant
            P(parent=TableCell(parent=tr, valuetype='string'),
              text=str(etudiant))

            # Moyenne de l'étudiant
            P(parent=TableCell(parent=tr,
                               valuetype='float',
                               value=etu_resultats['moyenne'],
                               stylename=style_note),
              text="{:.2f}".format(etu_resultats['moyenne']))

            # Rang de l'étudiant
            P(parent=TableCell(parent=tr,
                               valuetype='float',
                               value=etu_resultats['rang']),
              text="{}".format(etu_resultats['rang']))

            # Notes
            for note in etu_resultats['notes']:
                tc = TableCell(parent=tr)

                if isinstance(note, list) and len(note) == 1:
                    note = note[0]

                if isinstance(note, Note):
                    if note.est_note():
                        tc.setAttribute('valuetype', 'float')
                        tc.setAttribute('value', note.value)
                        tc.setAttribute('stylename', style_note)
                    P(text="{:.2f}".format(note), parent=tc)

                elif isinstance(note, list):
                    P(text=', '.join([
                        "{:.2f}".format(n) for n in note
                        if isinstance(n, Note)
                    ]),
                      parent=tc)

    ods.write(response)
    return response