Convertendo um excel xls em table HTML usando python

Posted on 23 \d\e dezembro \d\e 2010. Filed under: computers, python | Tags:, , , , , , , , |

import xlrd
from lxml.html import builder as E, tostring
from lxml.etree import ElementTree

def itermeth(obj, method, endattr):
    for index in xrange(getattr(obj, endattr)):
        yield getattr(obj, method)(index)

def xls_tree(xls_filename, header=True, tableattrs=None):
    if tableattrs is None:
        tableattrs = {}
    workbook = xlrd.open_workbook(xls_filename)
    head = E.HEAD(E.TITLE(xls_filename))
    body = E.BODY()
    for sheet in workbook.sheets():
        if sheet.nrows <= 0 or sheet.ncols <= 0:
            continue # sheet is empty
        table = E.TABLE(E.CAPTION(sheet.name), **tableattrs)
        container = E.THEAD()
        table.append(container)
        cellClass = E.TH
        for xlsrow in itermeth(sheet, 'row', 'nrows'):
            row = E.TR()
            container.append(row)
            if header:
                container = E.TBODY()
                table.append(container)
                cellClass = E.TD
                header = False
            for cell in xlsrow:
                row.append(cellClass(unicode(cell.value)))
        body.append(table)
    return ElementTree(E.HTML(head, body))
    

## Example usage:
html = xls_tree('/home/nosklo/Documentos/teste.xls', 
    tableattrs={'class': 'mytable', 'border': '2'})
# print to screen
print tostring(html, pretty_print=True)
# write to file
html.write('/tmp/resultado.html')
Anúncios
Ler Post Completo | Make a Comment ( 2 so far )

  • Blog Stats

    • 4,230 hits
  • contribua!

Liked it here?
Why not try sites on the blogroll...