Ejemplo n.º 1
0
def ar2workbook(ar, column_names=None):
    from openpyxl import Workbook
    from openpyxl.styles import Font
    # local import to avoid the following traceback:
    # Error in sys.exitfunc:
    # Traceback (most recent call last):
    #   File "/usr/lib/python2.7/atexit.py", line 24, in _run_exitfuncs
    #     func(*targs, **kargs)
    #   File "/openpyxl/writer/write_only.py", line 38, in _openpyxl_shutdown
    #     for path in ALL_TEMP_FILES:
    # TypeError: 'NoneType' object is not iterable

    # workbook = Workbook(guess_types=True)

    # removed `guess_types=True` because it caused trouble in openpyxl
    # 3.4.0 and because I don't know whether it is needed.

    workbook = Workbook()
    sheet = workbook.active
    sheet.title = sheet_name(ar.get_title())

    bold_font = Font(
        name='Calibri',
        size=11,
        bold=True,
    )

    fields, headers, widths = ar.get_field_info(column_names)

    for c, column in enumerate(fields):
        sheet.cell(row=1, column=c + 1).value = str(headers[c])
        sheet.cell(row=1, column=c + 1).font = bold_font
        # sheet.col(c).width = min(256 * widths[c] / 7, 65535)
        # 256 == 1 character width, max width=65535

    for c, column in enumerate(fields):
        for r, row in enumerate(ar.data_iterator, start=1):
            sf = column.field._lino_atomizer
            value = sf.full_value_from_object(row, ar)
            if type(value) == bool:
                value = value and 1 or 0
            elif isinstance(value, (Duration, Choice)):
                value = str(value)
            elif E.iselement(value):
                value = E.to_rst(value)
                # dd.logger.info("20160716 %s", value)
            elif isinstance(value, Promise):
                value = str(value)
            elif isinstance(value, IncompleteDate):
                if value.is_complete():
                    value = value.as_date()
                else:
                    value = str(value)
            elif isinstance(value, Model):
                value = str(value)
            sheet.cell(row=r + 1, column=c + 1).value = value

    return workbook
Ejemplo n.º 2
0
def ar2workbook(ar, column_names=None):
    from openpyxl import Workbook
    from openpyxl.styles import Font

    # local import to avoid the following traceback:
    # Error in sys.exitfunc:
    # Traceback (most recent call last):
    #   File "/usr/lib/python2.7/atexit.py", line 24, in _run_exitfuncs
    #     func(*targs, **kargs)
    #   File "/openpyxl/writer/write_only.py", line 38, in _openpyxl_shutdown
    #     for path in ALL_TEMP_FILES:
    # TypeError: 'NoneType' object is not iterable

    # workbook = Workbook(guess_types=True)

    # removed `guess_types=True` because it caused trouble in openpyxl
    # 3.4.0 and because I don't know whether it is needed.

    workbook = Workbook()
    sheet = workbook.active
    sheet.title = sheet_name(ar.get_title())

    bold_font = Font(name="Calibri", size=11, bold=True)

    fields, headers, widths = ar.get_field_info(column_names)

    for c, column in enumerate(fields):
        sheet.cell(row=1, column=c + 1).value = str(headers[c])
        sheet.cell(row=1, column=c + 1).font = bold_font
        # sheet.col(c).width = min(256 * widths[c] / 7, 65535)
        # 256 == 1 character width, max width=65535

    for c, column in enumerate(fields):
        for r, row in enumerate(ar.data_iterator, start=1):
            sf = column.field._lino_atomizer
            value = sf.full_value_from_object(row, ar)
            if type(value) == bool:
                value = value and 1 or 0
            elif isinstance(value, (Duration, Choice)):
                value = str(value)
            elif E.iselement(value):
                value = E.to_rst(value)
                # dd.logger.info("20160716 %s", value)
            elif isinstance(value, Promise):
                value = str(value)
            elif isinstance(value, IncompleteDate):
                if value.is_complete():
                    value = value.as_date()
                else:
                    value = str(value)
            elif isinstance(value, Model):
                value = str(value)
            sheet.cell(row=r + 1, column=c + 1).value = value

    return workbook
Ejemplo n.º 3
0
    def body(cls, self, ar):
        html = []
        for item in self.get_story(ar):
            if E.iselement(item):
                html.append(item)
            elif isinstance(item, type) and issubclass(item, Actor):
                html.append(ar.show(item, master_instance=self))
            else:
                raise Exception("Cannot handle %r" % item)

        return E.div(*html)
Ejemplo n.º 4
0
 def obj2html(self, ar, obj, text=None, **kwargs):
     """Return a html representation of a pointer to the given database
     object."""
     if text is None:
         text = (force_text(obj),)
     elif isinstance(text, basestring) or E.iselement(text):
         text = (text,)
     url = self.instance_handler(ar, obj)
     if url is None:
         return E.em(*text)
     return E.a(*text, href=url, **kwargs)
Ejemplo n.º 5
0
    def obj2html(self, ar, obj, text=None, **kwargs):
        """Return a html representation of a pointer to the given database
        object.

        """
        if text is None:
            text = (force_text(obj),)
        elif isinstance(text, six.string_types) or E.iselement(text):
            text = (text,)
        url = self.obj2url(ar, obj)
        if url is None:
            return E.em(*text)
        return self.href_button(url, text, **kwargs)
Ejemplo n.º 6
0
    def as_appy_pod_xml(cls, self, apr):
        from lino.utils.html2odf import html2odf, toxml

        chunks = []
        for item in self.get_story(apr.ar):
            if E.iselement(item):
                chunks.append(toxml(html2odf(item)))
            elif isinstance(item, type) and issubclass(item, Actor):
                sar = apr.ar.spawn(item, master_instance=self)
                chunks.append(apr.insert_table(sar))
            else:
                raise Exception("Cannot handle %r" % item)

        return ''.join(chunks)
Ejemplo n.º 7
0
 def story2odt(self, story, *args, **kw):
     "Yield a sequence of ODT chunks (as utf8 encoded strings)."
     from lino.core.actors import Actor
     from lino.core.tables import TableRequest
     for item in story:
         if E.iselement(item):
             yield toxml(html2odf(item))
         elif isinstance(item, type) and issubclass(item, Actor):
             sar = self.ar.spawn(item, *args, **kw)
             yield self.insert_table(sar)
         elif isinstance(item, TableRequest):
             # logger.info("20141211 story2odt %s", item)
             yield self.insert_table(item)
         elif isiterable(item):
             for i in self.story2odt(item, *args, **kw):
                 yield i
         else:
             raise Exception("Cannot handle %r" % item)
Ejemplo n.º 8
0
 def story2odt(self, story, *args, **kw):
     "Yield a sequence of ODT chunks (as utf8 encoded strings)."
     from lino.core.actors import Actor
     from lino.core.tables import TableRequest
     for item in story:
         if E.iselement(item):
             yield toxml(html2odf(item))
         elif isinstance(item, type) and issubclass(item, Actor):
             sar = self.ar.spawn(item, *args, **kw)
             yield self.insert_table(sar)
         elif isinstance(item, TableRequest):
             # logger.info("20141211 story2odt %s", item)
             yield self.insert_table(item)
         elif isiterable(item):
             for i in self.story2odt(item, *args, **kw):
                 yield i
         else:
             raise Exception("Cannot handle %r" % item)
Ejemplo n.º 9
0
    def show_story(self, ar, story, stripped=True, **kwargs):
        """Render the given story as reStructuredText to stdout."""
        from lino.core.actors import Actor
        from lino.core.requests import ActionRequest

        for item in story:
            if E.iselement(item):
                print(E.to_rst(item, stripped))
            elif isinstance(item, type) and issubclass(item, Actor):
                ar = item.default_action.request(parent=ar)
                self.show_table(ar, stripped=stripped, **kwargs)
            elif isinstance(item, ActionRequest):
                self.show_table(item, stripped=stripped, **kwargs)
                # print(item.table2rst(*args, **kwargs))
            elif isiterable(item):
                self.show_story(ar, item, stripped, **kwargs)
                # for i in self.show_story(ar, item, *args, **kwargs):
                #     print(i)
            else:
                raise Exception("Cannot handle %r" % item)
Ejemplo n.º 10
0
    def show_story(self, ar, story, stripped=True, **kwargs):
        """Render the given story as reStructuredText to stdout."""
        from lino.core.actors import Actor
        from lino.core.requests import ActionRequest

        for item in story:
            if E.iselement(item):
                print(E.to_rst(item, stripped))
            elif isinstance(item, type) and issubclass(item, Actor):
                ar = item.default_action.request(parent=ar)
                self.show_table(ar, stripped=stripped, **kwargs)
            elif isinstance(item, ActionRequest):
                self.show_table(item, stripped=stripped, **kwargs)
                # print(item.table2rst(*args, **kwargs))
            elif isiterable(item):
                self.show_story(ar, item, stripped, **kwargs)
                # for i in self.show_story(ar, item, *args, **kwargs):
                #     print(i)
            else:
                raise Exception("Cannot handle %r" % item)
Ejemplo n.º 11
0
 def html_func(self, html, **kw):
     """
     Render a string that is in HTML (not XHTML).
     """
     if not html:
         return ''
     if E.iselement(html):
         html = E.tostring(html)
     try:
         html = html2xhtml(html)
     except Exception as e:
         print(20150923, e)
     # logger.debug("20141210 html_func() got:<<<\n%s\n>>>", html)
     # print __file__, ">>>"
     # print html
     # print "<<<", __file__
     if isinstance(html, str):
         # some sax parsers refuse unicode strings.
         # appy.pod always expects utf-8 encoding.
         # See /blog/2011/0622.
         html = html.encode('utf-8')
         #~ logger.info("20120726 html_func() %r",html)
     return self.renderXhtml(html, **kw)
Ejemplo n.º 12
0
 def html_func(self, html, **kw):
     """
     Render a string that is in HTML (not XHTML).
     """
     if not html:
         return ''
     if E.iselement(html):
         html = E.tostring(html)
     try:
         html = html2xhtml(html)
     except Exception as e:
         print 20150923, e
     # logger.debug("20141210 html_func() got:<<<\n%s\n>>>", html)
     # print __file__, ">>>"
     # print html
     # print "<<<", __file__
     if isinstance(html, unicode):
         # some sax parsers refuse unicode strings.
         # appy.pod always expects utf-8 encoding.
         # See /blog/2011/0622.
         html = html.encode('utf-8')
         #~ logger.info("20120726 html_func() %r",html)
     return self.renderXhtml(html, **kw)
Ejemplo n.º 13
0
    def html_func(self, html, **kw):
        """
        Insert a chunk of HTML (not XHTML).
        This might be provided as a string or as an etree element.
        """

        if html is None or html == '':
            # Testing for `if not html:` caused a FutureWarning: The
            # behavior of this method will change in future versions.
            # Use specific 'len(elem)' or 'elem is not None' test
            # instead.
            return ''

        if E.iselement(html):
            html = E.tostring(html)

        try:
            html = html2xhtml(html)
        except Exception as e:
            raise Exception(
                "20150923 html2xhtml(%r) failed: %s" % (html, e))
        # logger.info("20160330 html_func() got:<<<\n%s\n>>>", html)
        # print(__file__, ">>>")
        # print(html)
        # print("<<<", __file__)
        try:
            return self.renderXhtml(html, **kw)
        except Exception as e:
            if not isinstance(html, six.string_types):
                raise
            # some sax parsers refuse unicode strings.
            # appy.pod always expects utf-8 encoding.
            # See /blog/2011/0622.
            html = html.encode('utf-8')
            # logger.info("20120726 renderXhtml(%r) failed : %s", html, e)
            return self.renderXhtml(html, **kw)
Ejemplo n.º 14
0
    def show_story(self, ar, story, stripped=True, **kwargs):
        """Render the given story as an HTML element. Ignore `stripped`
        because it makes no sense in HTML.

        """
        from lino.core.actors import Actor
        from lino.core.tables import TableRequest
        elems = []
        for item in story:
            if E.iselement(item):
                elems.append(item)
            elif isinstance(item, type) and issubclass(item, Actor):
                ar = item.default_action.request(parent=ar)
                elems.append(self.table2story(ar, **kwargs))
            elif isinstance(item, TableRequest):
                assert item.renderer is not None
                elems.append(self.table2story(item, **kwargs))
            elif isiterable(item):
                elems.append(self.show_story(ar, item, **kwargs))
                # for i in self.show_story(item, *args, **kwargs):
                #     yield i
            else:
                raise Exception("Cannot handle %r" % item)
        return E.div(*elems)
Ejemplo n.º 15
0
    def show_story(self, ar, story, stripped=True, **kwargs):
        """Render the given story as an HTML element. Ignore `stripped`
        because it makes no sense in HTML.

        """
        from lino.core.actors import Actor
        from lino.core.tables import TableRequest
        elems = []
        for item in story:
            if E.iselement(item):
                elems.append(item)
            elif isinstance(item, type) and issubclass(item, Actor):
                ar = item.default_action.request(parent=ar)
                elems.append(self.table2story(ar, **kwargs))
            elif isinstance(item, TableRequest):
                assert item.renderer is not None
                elems.append(self.table2story(item, **kwargs))
            elif isiterable(item):
                elems.append(self.show_story(ar, item, **kwargs))
                # for i in self.show_story(item, *args, **kwargs):
                #     yield i
            else:
                raise Exception("Cannot handle %r" % item)
        return E.div(*elems)