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')

Make a Comment

Deixe um comentário

2 Respostas to “Convertendo um excel xls em table HTML usando python”

RSS Feed for foobar + h2o Comments RSS Feed

Boa!
tem como fazer o inverso?
como seria?

Sim, o contrário seria usando o lxml para parsear o código html, e em seguida usar o xlwt para gerar o arquivo excel. Futuramente vou postar esta solução…


Where's The Comment Form?

  • Blog Stats

    • 6.066 hits
  • contribua!

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