def create_table(labels, results): document = odf_new_document('spreadsheet') body = document.get_body() table = odf_create_table("results") row = odf_create_row() rnbr = 1 for lang in sorted(results): cell = odf_create_cell() cell.set_value(lang, text=lang) row.set_cell(rnbr, cell) rnbr += 1 table.set_row(0, row) lnbr = 1 for i in range(len(labels)): row = odf_create_row() cell = odf_create_cell() cell.set_value(labels[i], text=labels[i]) row.set_cell(0, cell) rnbr = 1 for lang in sorted(results): cell = odf_create_cell() val = results[lang][i] cell.set_value(val, text="%.5f" % val, cell_type="float") row.set_cell(rnbr, cell) rnbr += 1 table.set_row(lnbr, row) lnbr += 1 body.append(table) document.save(target="__res2.ods", pretty=True)
def action_export_as_ods(self, resource, context, form): if lpod_is_install is False: msg = ERROR(u'Please install LPOD') return context.come_back(msg) # XXX Create a new process and send ODS file by mail for performances ? # XXX We do not export product without declination # XXX We do not export product without product model # Get list of groups groups = [] for option in UserGroup_Enumerate.get_options(): group = context.root.get_resource(option['name']) if group.get_property('use_default_price') is True: continue groups.append(group) # DB root = context.root shop = get_shop(resource) document = odf_new_document_from_type('spreadsheet') body = document.get_body() models = shop.get_resource('products-models').get_resources() for product_model in models: lines = [] # We create one TAB by product model table = odf_create_table(product_model.get_title()) search = root.search(product_model=str(product_model.get_abspath())) for brain in search.get_documents(): product = root.get_resource(brain.abspath) for d in product.search_resources(cls=Declination): # Ref - Declination name - Declination title line = [product.get_property('reference'), d.name, d.get_declination_title().encode('utf-8')] # Stock line.append(str(d.get_quantity_in_stock())) # Price by group (HT or TTC) for group in groups: k_price = {'id_declination': d.name, 'prefix': group.get_prefix(), 'pretty': True} if group.get_property('show_ht_price'): price = product.get_price_without_tax(**k_price) else: price = product.get_price_with_tax(**k_price) line.append(str(price)) # Add row lines.append(','.join(line)) data = '\n'.join(lines) table = import_from_csv(StringIO(data), product_model.name) body.append(table) # Extport as ODS f = StringIO() document.save(f) content = f.getvalue() f.close() # Return ODS context.set_content_type('application/vnd.oasis.opendocument.spreadsheet') context.set_content_disposition('attachment', 'export.ods') return content
def test_swap(D, table_ini): print("Test swap rows/cols from table", D.lines, "rows", D.cols, "cols") table = odf_create_table("swapped", D.lines, D.cols) C = chrono() for col in range(D.cols): values = table_ini.get_column_values(col) table.set_row_values(col, values) C.delta() print("Size of swapped table :", table.get_size()) if DEBUG: print(table.to_csv()) print("-" * 50)
def test_width_height(self): table = odf_create_table(u"A Table", width=1, height=2) expected = ('<table:table table:name="A Table">' '<table:table-column/>' '<table:table-row>' '<table:table-cell/>' '</table:table-row>' '<table:table-row>' '<table:table-cell/>' '</table:table-row>' '</table:table>') self.assertEqual(table.serialize(), expected)
def test_get_table_width_after(self): table = odf_create_table(u"Empty") self.assertEqual(table.get_table_width(), 0) self.assertEqual(table.get_table_height(), 0) # The first row creates the columns table.append_row(odf_create_row(width=5)) self.assertEqual(table.get_table_width(), 5) self.assertEqual(table.get_table_height(), 1) # The subsequent ones don't table.append_row(odf_create_row(width=5)) self.assertEqual(table.get_table_width(), 5) self.assertEqual(table.get_table_height(), 2)
def test_swap(D, table_ini): print "Test swap rows/cols from table", D.lines, "rows", D.cols, "cols" table = odf_create_table(u"swapped", D.lines, D.cols) C = chrono() for col in xrange(D.cols): values = table_ini.get_column_values(col) table.set_row_values(col, values) C.delta() print "Size of swapped table :", table.get_size() if DEBUG: print table.to_csv() print "-" * 50
def test_get_table_width_after(self): table = odf_create_table(u"Empty") self.assertEqual(table.get_width(), 0) self.assertEqual(table.get_height(), 0) # The first row creates the columns table.append_row(odf_create_row(width=5)) self.assertEqual(table.get_width(), 5) self.assertEqual(table.get_height(), 1) # The subsequent ones don't table.append_row(odf_create_row(width=5)) self.assertEqual(table.get_width(), 5) self.assertEqual(table.get_height(), 2)
def test_append_rows(D): print "Test append_row", D.lines, "rows", D.cols, "cols" table = odf_create_table(u"Table") C = chrono() for line in xrange(D.lines): row = odf_create_row() row.set_values(D.py_table0[line]) table.append_row(row) C.delta() print "Size of table :", table.get_size() if DEBUG: print table.to_csv() print "-" * 50
def test_append_rows(D): print("Test append_row", D.lines, "rows", D.cols, "cols") table = odf_create_table("Table") C = chrono() for line in range(D.lines): row = odf_create_row() row.set_values(D.py_table0[line]) table.append_row(row) C.delta() print("Size of table :", table.get_size()) if DEBUG: print(table.to_csv()) print("-" * 50)
def GET(self, resource, context): if lpod_is_install is False: msg = ERROR(u'Please install LPOD') return context.come_back(msg) document = odf_new_document_from_type('text') body = document.get_body() root = context.root table = odf_create_table(u"Table 1", width=5, height=1, style='table-cell') for brain in root.search(format='product').get_documents(): # Get product product = root.get_resource(brain.abspath) cover = product.get_resource(product.get_property('cover')) # Add line row = odf_create_row(width=5) cell = odf_create_cell(u"") file = context.database.fs.open(cover.handler.key) local_uri = document.add_file(file) image_frame = odf_create_image_frame(local_uri, size=('5cm', '5cm'), position=('0cm', '0cm'), anchor_type='as-char') paragraph = cell.get_element('text:p') paragraph.append(image_frame) cell.append(paragraph) row.set_cell(0, cell) row.set_cell_value(1, brain.reference) row.set_cell_value(2, brain.title) row.set_cell_value(3, u'%s' % product.get_price_without_tax()) table.append_row(row) # Get declinations for d in product.search_resources(cls=Declination): price = d.parent.get_price_without_tax(id_declination=d.name, pretty=True) row = odf_create_row(width=5) row.set_cell_value(1, 'reference') row.set_cell_value(2, d.get_declination_title()) row.set_cell_value(3, u'%s' % price) row.set_cell_value(4, d.get_property('stock-quantity')) table.append(row) body.append(table) f = StringIO() document.save(f) content = f.getvalue() f.close() context.set_content_type('application/vnd.oasis.opendocument.text') context.set_content_disposition('attachment', 'export.odt') return content
def create_table_summary(document, data, headers=None, style=None): table = odf_create_table(u"Table") # Insert headers and apply base cell style to the cells if headers: odt_row = odf_create_row() odt_row.set_values(headers) for cell in odt_row.traverse(): cell.set_style(STYLES[TABLE_CELL_BASE]) odt_row.set_cell(x=cell.x, cell=cell) table.set_row(0, odt_row) for indx, row in enumerate(data): odt_row = odf_create_row() values = [] for val in row: if not val: values.append(u"") if isinstance(val, (basestring, unicode, int, float)): values.append(val) # In assessment summary table score is a tuple (conclusion, color) if isinstance(val, tuple): values.append(val[0]) odt_row.set_values(values) # Color the cell, based on the score for j, cell in enumerate(odt_row.traverse()): # first column from row gets base cell style if j == 0: cell.set_style(STYLES[TABLE_CELL_BASE]) odt_row.set_cell(x=cell.x, cell=cell) continue color_val = row[j][1] colored_style = "{}{}".format(TABLE_CELL_AS_VALUE, color_val) # other rows need too be colored cell.set_style(STYLES[colored_style]) odt_row.set_cell(x=cell.x, cell=cell) table.set_row(indx + 1, odt_row) # apply_table_cell_base_style(document, table) return table
def test_random_set_value(D): print "Test random set_value", D.lines, "rows", D.cols, "cols" table = odf_create_table(u"Table") cpt = 0 C = chrono() for line in D.rnd_line: for col in range(D.cols): table.set_value((col, line), cpt) cpt += 1 C.delta() print cpt, "values entered" print "Size of table :", table.get_size() if DEBUG: print table.to_csv() print "-" * 50 return table
def test_random_set_value(D): print("Test random set_value", D.lines, "rows", D.cols, "cols") table = odf_create_table("Table") cpt = 0 C = chrono() for line in D.rnd_line: for col in range(D.cols): table.set_value((col, line), cpt) cpt += 1 C.delta() print(cpt, "values entered") print("Size of table :", table.get_size()) if DEBUG: print(table.to_csv()) print("-" * 50) return table
def action_export(self, resource, context, form): root = context.root results = context.root.search(format=self.export_resource.class_id) if not len(results): context.message = ERR_NO_DATA return context.query['batch_start'] = context.query['batch_size'] = 0 # Create ODS header_style = odf_create_style('table-cell', area='text', bold=True) document = odf_new_document_from_type('spreadsheet') document.insert_style(header_style, automatic=True) body = document.get_body() table = odf_create_table(u'Table') # Add the header row = odf_create_row() line = self.get_header(resource, context) row.set_values(line, style=header_style) table.append_row(row) # Fill content for item_brain in results.get_documents(): item_resource = root.get_resource(item_brain.abspath) line = self.get_row(resource, context, item_resource) row = odf_create_row() try: row.set_values(line) except Exception: context.message = ERROR(u'Error on line %s' % line) return table.append_row(row) body.append(table) # Extport as ODS f = StringIO() document.save(f) content = f.getvalue() f.close() # Return ODS context.set_content_type( 'application/vnd.oasis.opendocument.spreadsheet') context.set_content_disposition('attachment', self.get_filename(resource)) return content
def test_repeated(D): print "test random repeated lines", D.lines, "rows", D.cols, "cols" table = odf_create_table(u"Table") C = chrono() for line in xrange(D.lines): row = odf_create_row() row.set_values([(line * 10 + x) for x in range(D.cols)]) row.set_repeated(line) #if DEBUG: # print D.rnd_line[line], "=>", row.get_values(), row.get_repeated() table.set_row(D.rnd_line[line], row) C.delta() print "Size of table :", table.get_size() if DEBUG: print table.to_csv() print "-" * 50 return table
def test_repeated(D): print("test random repeated lines", D.lines, "rows", D.cols, "cols") table = odf_create_table("Table") C = chrono() for line in range(D.lines): row = odf_create_row() row.set_values([(line * 10 + x) for x in range(D.cols)]) row.set_repeated(line) #if DEBUG: # print D.rnd_line[line], "=>", row.get_values(), row.get_repeated() table.set_row(D.rnd_line[line], row) C.delta() print("Size of table :", table.get_size()) if DEBUG: print(table.to_csv()) print("-" * 50) return table
def spreadsheet_to_text(indoc, outdoc): inbody = indoc.get_body() outbody = outdoc.get_body() # Copy tables for intable in inbody.get_tables(): # clone/rstrip the table clone = intable.clone() clone.rstrip(aggressive=True) # Skip empty table if clone.get_size() == (0, 0): continue # At least OOo Writer doesn't like formulas referencing merged # cells, so expand outtable = odf_create_table(clone.get_name(), style=clone.get_style()) # Columns for column in clone.traverse_columns(): outtable.append(column) # Rows for inrow in clone.traverse(): outrow = odf_create_row(style=inrow.get_style()) # Cells for cell in inrow.traverse(): # Formula formula = cell.get_formula() if formula is not None: if formula.startswith('oooc:'): formula = oooc_to_ooow(formula) else: # Found an OpenFormula test case raise NotImplementedError, formula cell.set_formula(formula) outrow.append(cell) outtable.append_row(outrow) outbody.append(outtable) # Separate tables with an empty line outbody.append(odf_create_paragraph()) # Copy styles for family in ('table', 'table-column', 'table-row', 'table-cell'): for style in indoc.get_styles(family=family): automatic = (style.get_parent().get_tag() == 'office:automatic-styles') default = style.get_tag() == 'style:default-style' outdoc.insert_style(style, automatic=automatic, default=default)
def action_export(self, resource, context, form): root = context.root results = context.root.search(format=self.export_resource.class_id) if not len(results): context.message = ERR_NO_DATA return context.query['batch_start'] = context.query['batch_size'] = 0 # Create ODS header_style = odf_create_style('table-cell', area='text', bold=True) document = odf_new_document_from_type('spreadsheet') document.insert_style(header_style, automatic=True) body = document.get_body() table = odf_create_table(u'Table') # Add the header row = odf_create_row() line = self.get_header(resource, context) row.set_values(line, style=header_style) table.append_row(row) # Fill content for item_brain in results.get_documents(): item_resource = root.get_resource(item_brain.abspath) line = self.get_row(resource, context, item_resource) row = odf_create_row() try: row.set_values(line) except Exception: context.message = ERROR(u'Error on line %s' % line) return table.append_row(row) body.append(table) # Extport as ODS f = StringIO() document.save(f) content = f.getvalue() f.close() # Return ODS context.set_content_type('application/vnd.oasis.opendocument.spreadsheet') context.set_content_disposition('attachment', self.get_filename(resource)) return content
def convert_table(node, context): styles = context["styles"] cell_style = styles.get('cell_style') if cell_style is None: cell_style = odf_create_style('table-cell', u"odf_table.A1", padding=u"0.049cm", border=u"0.002cm solid #000000") context['doc'].insert_style(cell_style, automatic=True) styles['cell_style'] = cell_style for tgroup in node: if tgroup.tagname != "tgroup": warn('node "%s" not supported in table' % tgroup.tagname) continue columns_number = 0 odf_table = None for child in tgroup: tagname = child.tagname if tagname == "thead" or tagname == "tbody": # Create a new table with the info columns_number if odf_table is None: context["tables_number"] += 1 # TODO Make it possible directly with odf_create_table odf_table = odf_create_table(name="table%d" % context["tables_number"]) columns = odf_create_column(repeated=columns_number) odf_table.append_element(columns) # Convert! if tagname == "thead": header = odf_create_header_rows() odf_table.append_element(header) _convert_table_rows(header, child, context, cell_style=cell_style.get_style_name()) else: _convert_table_rows(odf_table, child, context, cell_style=cell_style.get_style_name()) elif tagname == "colspec": columns_number += 1 else: warn('node "%s" not supported in tgroup' % child.tagname) continue context["top"].append_element(odf_table)
def test_set_rows(D): print("Test random set_row", D.lines, "rows", D.cols, "cols") table = odf_create_table("Table") C = chrono() for line in range(D.lines): row = odf_create_row() row.set_values(D.py_table0[line]) if DEBUG: print(D.rnd_line[line], "=>", D.py_table0[line]) table.set_row(D.rnd_line[line], row) if DEBUG: print(table.to_csv()) C.delta() print("Size of table :", table.get_size()) if DEBUG: print(table.to_csv()) print("-" * 50) return table
def test_set_rows(D): print "Test random set_row", D.lines, "rows", D.cols, "cols" table = odf_create_table(u"Table") C = chrono() for line in xrange(D.lines): row = odf_create_row() row.set_values(D.py_table0[line]) if DEBUG: print D.rnd_line[line], "=>", D.py_table0[line] table.set_row(D.rnd_line[line], row) if DEBUG: print table.to_csv() C.delta() print "Size of table :", table.get_size() if DEBUG: print table.to_csv() print "-" * 50 return table
def create_table(document, data, headers=None, style=None): table = odf_create_table(u"Table") if headers: odt_row = odf_create_row() odt_row.set_values(headers) table.set_row(0, odt_row) for indx, row in enumerate(data): odt_row = odf_create_row() values = [] for val in row: if not val: values.append(u"") continue if isinstance(val, (datetime.date, datetime.datetime)): values.append(val.strftime('%Y %b %d')) continue if isinstance(val, (basestring, unicode, int, float)): values.append(val) continue # In assessment summary table score is a tuple (conclusion, color) if isinstance(val, tuple): values.append(val[0]) continue # ItemList type values.append(', '.join(val.rows)) odt_row.set_values(values) table.set_row(indx + 1, odt_row) apply_table_cell_base_style(document, table) return table
def __init__(self, name): self.document = document = odf_new_document('spreadsheet') self.table = table = odf_create_table(name) document.get_body().append(table) document.insert_style(self.header_style, automatic=True)
Transpose a table. Create a spreadsheet table (example: 50 rows and 20 columns), and subsequently create a new table in a separate sheet where the columns and rows are now swapped (e.g. 20 rows and 50 columns). """ import os # Import from lpod from lpod.document import odf_new_document from lpod.table import odf_create_table, odf_create_row if __name__ == "__main__": spreadsheet = odf_new_document('spreadsheet') # Populate the table in the spreadsheet body = spreadsheet.get_body() table = odf_create_table(u"Table") body.append(table) lines = 50 cols = 20 for line in range(lines): row = odf_create_row() for column in range(cols): row.set_value(column, "%s%s" % (chr(65 + column), line + 1)) table.append(row) print "Size of Table :", table.get_size() table2 = odf_create_table(u"Symetry")
# 2- Your environment (=> a table) # -------------------------------- heading = odf_create_heading(1, text=u'Your environment') body.append(heading) data = [] # lpOD Version data.append([u'lpOD library version', __version__]) # Python version data.append([u'Python version', '%d.%d.%d' % version_info[:3]]) # Creation / Insertion table = odf_create_table(u'table1', width=2, height=2, style=u"Standard") table.set_values(data) body.append(table) # 3- Description (=> footnote & => highlight) # ------------------------------------------- heading = odf_create_heading(1, text=u'Description') body.append(heading) # A paragraph with a note text = u'The lpOD project is made to generate easily OpenDocuments.' paragraph = odf_create_paragraph(text, style=u"Standard") paragraph.insert_note(after=u"lpOD project", note_id='note1', citation=u'1', body=u'http://lpod-project.org/')
# -*- coding: UTF-8 -*- from lpod.document import odf_new_document from lpod.heading import odf_create_heading from lpod.paragraph import odf_create_paragraph document = odf_new_document('text') body = document.get_body() # Let's add another section to make our document clear: body.append(odf_create_heading(1, u"Tables")) body.append(odf_create_paragraph(u"A 3x3 table:")) # Creating a table : from lpod.table import odf_create_table table = odf_create_table(u"Table 1", width=3, height=3) body.append(table)
def test_style(self): table = odf_create_table(u"A Table", style=u"A Style") expected = ('<table:table table:name="A Table" ' 'table:style-name="A Style"/>') self.assertEqual(table.serialize(), expected)
def test_get_table_size_empty(self): table = odf_create_table(u"Empty") self.assertEqual(table.get_table_size(), (0, 0))
from lpod.table import odf_create_table from lpod.style import odf_create_table_cell_style from lpod.style import make_table_cell_border_string from lpod.style import odf_create_style, rgb2hex # Hello messages print 'lpod installation test' print ' Version : %s' % __version__ print ' Installation path : %s' % __installation_path__ print print 'Generating test_output/use_case3.ods ...' document = odf_new_document('spreadsheet') body = document.get_body() table = odf_create_table(u'use_case3') for y in xrange(0, 256, 8): row = odf_create_row() for x in xrange(0, 256, 32): cell_value = (x, y, (x+y) % 256 ) border_rl = make_table_cell_border_string( thick = '0.20cm', color = 'white' ) border_bt = make_table_cell_border_string( thick = '0.80cm', color = 'white', ) style = odf_create_table_cell_style( color = 'grey' ,
def test_print_false(self): table = odf_create_table(u"Hidden", printable=False) expected = '<table:table table:name="Hidden" table:print="false"/>' self.assertEqual(table.serialize(), expected)
from lpod.document import odf_new_document from lpod.table import odf_create_table, odf_create_cell from random import randrange #import lpod_vle from lpod_vle.of_syntax import of_formula, of_intro, of_reference, of_range_address, of_column, of_row from lpod_vle.of_stats import of_average, of_min, of_max #We create a spreadsheet just for the example doc = odf_new_document('spreadsheet') body = doc.get_body() table = odf_create_table("Data", width=5, height=5) body.append(table) c = 0 l = 0 for c in range(5): for l in range(5): v = randrange(0, 1000) table.set_value((c, l), v) #Then, we write some statistics about the data in a new sheet table = odf_create_table('Stats', width=3, height=2) body.append(table) table.set_value((0, 0), "Average") table.set_value((1, 0), "Maximum") table.set_value((2, 0), "Minimum") #average formula = of_formula( of_intro(),
result.append(tmp2) #we update the status places_status[data[index][2]] = places_status[data[index][2]] + \ (beginning - places_status[data[index][2]])+(end - beginning) line_read.append(index) ### #Second step : write the data in an ods file ### document = odf_new_document('spreadsheet') body = document.get_body() table = odf_create_table('Data') body.append(table) for i in range(len(result[0])): row = odf_create_row() cell = odf_create_cell("Place "+str(places[i])) row.append_cell(cell) for j in range(len(result)): cell = odf_create_cell(result[j][i]) row.append_cell(cell) table.append_row(row) ### #Third step : create our chart ### table = odf_create_table('Gantt')
#!/usr/bin/env python # -*- coding: UTF-8 -*- # ok lpod 1.0 """ Create a spreadsheet with two tables, using some named ranges. """ import os # Import from lpod from lpod.document import odf_new_document from lpod.table import odf_create_table if __name__ == "__main__": document = odf_new_document('spreadsheet') body = document.get_body() table = odf_create_table(u"First Table") body.append(table) # populate the table : for i in range(10): table.set_value((1, i), (i + 1)**2) table.set_value("A11", "Total:") # lets define a named range for the 10 values : crange = "B1:B10" name = "squares_values" table_name = table.get_name() table.set_named_range(name, crange, table_name) # we can define a single cell range, using notation "B11" or (1, 10) : table.set_named_range('total', (1, 10), table_name)
from lpod.table import odf_create_cell, odf_create_row from lpod.table import odf_create_table from lpod.style import odf_create_table_cell_style from lpod.style import make_table_cell_border_string from lpod.style import odf_create_style, rgb2hex # Hello messages print 'lpod installation test' print ' Version : %s' % __version__ print ' Installation path : %s' % __installation_path__ print print 'Generating color chart in my_color_chart.ods ...' document = odf_new_document('spreadsheet') body = document.get_body() table = odf_create_table(u'chart') for y in xrange(0, 256, 8): row = odf_create_row() for x in xrange(0, 256, 32): cell_value = (x, y, (x + y) % 256) border_rl = make_table_cell_border_string(thick='0.20cm', color='white') border_bt = make_table_cell_border_string( thick='0.80cm', color='white', ) style = odf_create_table_cell_style( color='grey', background_color=cell_value, border_right=border_rl,
text = document_source.get_body().get_text(recursive=True) for c in "():;!.,[]{}#@/\\=-_+*#@`\"'": text = text.replace(c, ' ') # slow algorithm words = text.split() print "nb of words:", len(words) frequences = {} for word in words: frequences[word] = frequences.get(word, 0) + 1 print "unique words found:", len(frequences) # Populate the table in the spreadsheet body = spreadsheet.get_body() table = odf_create_table(u"Frequency Table") body.append(table) sorted = [(value, key) for key, value in frequences.iteritems()] sorted.sort() sorted.reverse() # one solution : #for value, key in sorted: # row = odf_create_row() # row.set_value(0, key) # row.set_value(1, value) # Cell type is guessed. # table.append_row(row) # another solution :
from lpod.table import odf_create_table from lpod.style import odf_create_table_cell_style from lpod.style import make_table_cell_border_string from lpod.style import odf_create_style, rgb2hex # Hello messages print 'lpod installation test' print ' Version : %s' % __version__ print ' Installation path : %s' % __installation_path__ print print 'Generating color chart in my_color_chart.ods ...' document = odf_new_document('spreadsheet') body = document.get_body() table = odf_create_table(u'chart') for y in xrange(0, 256, 8): row = odf_create_row() for x in xrange(0, 256, 32): cell_value = (x, y, (x+y) % 256 ) border_rl = make_table_cell_border_string( thick = '0.20cm', color = 'white' ) border_bt = make_table_cell_border_string( thick = '0.80cm', color = 'white', ) style = odf_create_table_cell_style( color = 'grey' ,
paragraph = odf_create_paragraph('Standard') # 72 ppp frame = odf_create_frame('frame_%d' % numero, 'Graphics', str(width / 72.0) + 'in', str(height / 72.0) + 'in') image = odf_create_image(internal_name) frame.append_element(image) paragraph.append_element(frame) body.append_element(paragraph) # And store the data container = document.container container.set_part(internal_name, samples.open(filename).read()) elif isinstance(handler, CSVFile): table = odf_create_table(u"table %d" % numero, style=u"Standard") for csv_row in handler.get_rows(): size = len(csv_row) row = odf_create_row() for value in csv_row: cell = odf_create_cell(value) row.append_element(cell) table.append_element(row) for i in xrange(size): column = odf_create_column(style=u"Standard") table.insert_element(column, FIRST_CHILD) body.append_element(table) else: paragraph = odf_create_paragraph(u"Not image / csv", style=u"Standard") body.append_element(paragraph)
def test_print(self): table = odf_create_table(u"Printable") expected = '<table:table table:name="Printable"/>' self.assertEqual(table.serialize(), expected)
vals = line.split(",") rnbr = 0 for val in vals: cell = odf_create_cell() if lnbr < 2 or rnbr < 1: #table.set_value((rnbr, lnbr), val) cell.set_value(val, text=val) else: #table.set_value((rnbr, lnbr), float(val)) cell.set_value(float(val), text="%.5f" % float(val), cell_type="float") row.set_cell(rnbr, cell) rnbr = rnbr + 1 table.set_row(lnbr, row) lnbr = lnbr + 1 document = odf_new_document('spreadsheet') body = document.get_body() for csv_path in sorted(os.listdir('.')): if csv_path.endswith("-2018.csv"): lang = csv_path[:2] print(lang) table = odf_create_table(lang) createTable(csv_path, table) body.append(table) document.save(target="__res.ods", pretty=True)
def test_print_ranges_list(self): table = odf_create_table(u"Ranges", print_ranges=['E6:K12', 'P6:R12']) expected = ('<table:table table:name="Ranges" ' 'table:print-ranges="E6:K12 P6:R12"/>') self.assertEqual(table.serialize(), expected)
def test_is_row_empty(self): table = odf_create_table(u"Empty", width=10, height=20) for y in xrange(20): self.assertEqual(table.is_row_empty(y), True)
def test_get_table_by_position(self): body = self.body.clone() body.append_element(odf_create_table(u"New Table")) table = body.get_table_by_position(3) self.assertEqual(table.get_table_name(), u"New Table")
def test_is_column_empty(self): table = odf_create_table(u"Empty", width=10, height=20) for x in xrange(10): self.assertEqual(table.is_column_empty(x), True)
from lpod.document import odf_new_document from lpod.table import odf_create_table from random import randrange #We create a spreadsheet just for the example doc = odf_new_document('spreadsheet') body = doc.get_body() table = odf_create_table("Data", width=5, height=5) body.append(table) c = 0 l = 0 for c in range(5): for l in range(5): v = randrange(0, 1000) table.set_value((c, l), v) #we add the xml files that will contain the chart informations from chart import add_chart_structure_in_document chart_directory = add_chart_structure_in_document(doc) #we need an access to the office:automatic-styles element from lpod.xmlpart import odf_xmlpart chart_content = odf_xmlpart(chart_directory + '/content.xml', doc) styles = chart_content.get_element("office:automatic-styles") #we add informations about style from chart_style import odf_create_chart_title_style from chart_style import odf_create_chart_legend_style from chart_style import odf_create_chart_plot_area_style from chart_style import odf_create_chart_axis_style from chart_style import odf_create_chart_axis_title_style
# 3- Your environment (=> a table) # -------------------------------- heading = odf_create_heading(1, text=u'Your environment') body.append(heading) data = [] # lpOD Version data.append([u'lpOD library version', __version__]) # Python version data.append([u'Python version', '%d.%d.%d' % version_info[:3]]) # Creation / Insertion table = odf_create_table(u'table1', width=2, height=2, style=u"Standard") table.set_values(data) body.append(table) # 4- Description (=> footnote & => highlight) # ------------------------------------------- heading = odf_create_heading(1, text=u'Description') body.append(heading) # A paragraph with a note text = u'The lpOD project is made to generate easily OpenDocuments.' paragraph = odf_create_paragraph(text, style=u"Standard") paragraph.insert_note(after=u"lpOD project", note_id='note1', citation=u'1',
width, height = image.size paragraph = odf_create_paragraph('Standard') # 72 ppp frame = odf_create_frame('frame_%d' % numero, 'Graphics', str(width / 72.0) + 'in', str(height / 72.0) + 'in') image = odf_create_image(internal_name) frame.append(image) paragraph.append(frame) body.append(paragraph) # And store the data container = document.container container.set_part(internal_name, open(path).read()) elif mimetype in ('text/csv', 'text/comma-separated-values'): table = odf_create_table(u"table %d" % numero, style=u"Standard") csv = reader(open(path)) for line in csv: size = len(line) row = odf_create_row() for value in line: cell = odf_create_cell(value) row.append(cell) table.append(row) for i in xrange(size): column = odf_create_column(style=u"Standard") table.insert(column, FIRST_CHILD) body.append(table) else: paragraph = odf_create_paragraph(u"Not image / csv", style=u"Standard") body.append(paragraph)
text = document_source.get_body().get_text(recursive=True) for c in "():;!.,[]{}#@/\\=-_+*#@`\"'" : text = text.replace(c,' ') # slow algorithm words = text.split() print "nb of words:", len(words) frequences = {} for word in words: frequences[word] = frequences.get(word, 0) + 1 print "unique words found:", len(frequences) # Populate the table in the spreadsheet body = spreadsheet.get_body() table = odf_create_table(u"Frequency Table") body.append(table) sorted = [ (value, key) for key, value in frequences.iteritems() ] sorted.sort() sorted.reverse() # one solution : #for value, key in sorted: # row = odf_create_row() # row.set_value(0, key) # row.set_value(1, value) # Cell type is guessed. # table.append_row(row) # another solution :
# -*- coding: UTF-8 -*- from lpod.document import odf_new_document from lpod.table import odf_create_table document = odf_new_document('spreadsheet') body = document.get_body() table = odf_create_table(u"Empty Table") table.set_value('A1', "Hello World") body.append(table)
def test_display(self): table = odf_create_table(u"Displayed") expected = '<table:table table:name="Displayed"/>' self.assertEqual(table.serialize(), expected)
# Import from lpod from lpod.document import odf_new_document from lpod.table import odf_create_table if __name__ == "__main__": # creating an empty spreadsheet document: document = odf_new_document('spreadsheet') # Each sheet of a spreadsheet is a table: # setting drom the beginning width (columns) and height (rows) # is not mandatory, but a good practice, since lpod don't check # actual existence of cells body = document.get_body() table = odf_create_table(u"First Table", width=20, height=3) body.append(table) # A table contains rows, we can append some more. for r in range(2): table.append_row() print "rows in the table (3+2):", len(table.get_rows()) # A row contains cells for row in table.get_rows(): print "row, nb of cells ", row.y, len(row.get_cells()) last_row = table.get_row(-1) print "nb of cells of the last row:", len(last_row.get_cells()) # cell can have different kind of values
def test_display_false(self): table = odf_create_table(u"Hidden", display=False) expected = '<table:table table:name="Hidden" table:display="false"/>' self.assertEqual(table.serialize(), expected)
def test_is_column_empty_no(self): table = odf_create_table(u"Not Empty", width=10, height=20) table.set_cell_value((4, 9), u"Bouh !") self.assertEqual(table.is_column_empty(4), False)
# List of products in a list : product_list = odf_create_list() body.append(product_list) for product in catalog: item = odf_create_list_item(u"%-10s, price: %.2f €" % ( product.name, product.price)) product_list.append(item) title12 = odf_create_heading(2, u"Your command") body.append(title12) command = {0 : 1, 1 : 12, 2 : 3, 4 : 5 } # A table in the text document : table = odf_create_table(u"Table") body.append(table) row = odf_create_row() row.set_values([u"Product", u"Price", u"Quantity", u"Amount"]) table.set_row("A1", row) # or: table.set_row(0, row) row_number = 0 for item, quantity in command.iteritems(): prod = catalog[item] row = odf_create_row() row.set_value("A", prod.name) #or : row.set_value(0, prod.name) cell = odf_create_cell() cell.set_value(prod.price, text = u"%.2f €" % prod.price, currency = u"EUR", cell_type="float") row.set_cell("B", cell)
# Import from lpod from lpod.document import odf_new_document from lpod.table import odf_create_table if __name__=="__main__": # creating an empty spreadsheet document: document = odf_new_document('spreadsheet') # Each sheet of a spreadsheet is a table: # setting drom the beginning width (columns) and height (rows) # is not mandatory, but a good practice, since lpod don't check # actual existence of cells body = document.get_body() table = odf_create_table(u"First Table", width = 20, height = 3) body.append(table) # A table contains rows, we can append some more. for r in range(2): table.append_row() print "rows in the table (3+2):", len(table.get_rows()) # A row contains cells for row in table.get_rows(): print "row, nb of cells ", row.y, len(row.get_cells()) last_row = table.get_row(-1) print "nb of cells of the last row:", len(last_row.get_cells()) # cell can have different kind of values
# Import from lpod from lpod.document import odf_new_document from lpod.table import odf_create_table, odf_create_row, odf_create_cell def suite(n): if n % 2 == 0: return n / 2 return 3 * n + 1 if __name__=="__main__": spreadsheet = odf_new_document('spreadsheet') # Populate the table in the spreadsheet body = spreadsheet.get_body() table = odf_create_table(u"Big Table") body.append(table) lines = 1000 cols = 100 for line in range(lines): row = odf_create_row() values = [] n = line for i in range(cols): values.append(n) n = suite(n) row.set_values(values) table.append(row)