Coverage for lino/utils/odsreader.py : 85%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# -*- coding: UTF-8 -*- # Copyright 2012-2016 Luc Saffre # License: BSD (see file COPYING for details)
(OpenOffice.org spreadsheet).
Thanks to Marco Conti and gtr for their blog post `Read an ODS file with Python and Odfpy <http://www.marco83.com/work/173/read-an-ods-file-with-python-and-odfpy/>`_ which was a valuable source of inspiration to me. Unlike Marco's reader this one doesn't store any data in memory, it just loops over the rows.
OdsReader is used to import data from .ods files into a Django database using a :ref:`dpy` fixture, but not limited to this usage.
State : works for me, but very young and probably full of bugs.
Usage example:
The following code reads a file :srcref:`odsreader_sample.ods` and prints a line of text for each row of data.
>>> class Sample(OdsReader): ... filename = srcpath('odsreader_sample.ods') ... headers = ["N°", "Prénom", "Last name", "Country", "City", "Language"] ... column_names = 'no first_name last_name country city language'.split() ... >>> for row in Sample().rows(): ... print( "%(first_name)s %(last_name)s from %(city)s" % row) Rudi Rutté from Eupen Romain Raffault from Liège Rando Roosi from Tallinn Rik Rozenbos from Antwerpen Robin Rood from London
(Note: these are fictive person names from :mod:`lino.modlib.users.fixtures.demo`).
""" # ~ logging.basicConfig(level='DEBUG') # uncomment this when debugging
"""Abstract base class. For each .ods file you are probably creating a subclass of this.
""" """The full path name of the .ods file to be read.
"""
"""A list of unicode strings, one for each column in the file. The headers specified here must match exactly those found in the .ods file.
"""
setattr(self, k, v)
"""This will be called for each recognized data row and may perform a conversion before yielding it. Subclasses may override this.
""" return cells
""" Yields the data rows found in this .ods file. """ self.column_names = self.headers
else:
#~ if len(cells): else: logger.debug("Unrecognized row %s", cells)
""" Like :class:`SimpleOdsReader`, but each row is converted to an :class:`lino.utils.AttrDict`. This requires you to specifiy, besides the :attr:`SimpleOdsReader.headers` attrribute, another list of pure ASCII strings which must be valid Python attribute names.
"""
name = self.column_names[i] if name: d[name] = None i += 1 #~ logger.info("20121122 cells2row %s -> %s",cells,d)
import doctest doctest.testmod()
_test() |