Convertendo um excel xls em table HTML usando python
Posted on 23 \d\e dezembro \d\e 2010. Filed under: computers, python | Tags:etree, example, excel, html, lxml, parse, python, serialization, table |
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
Comments RSS Feed
Where's The Comment Form?
Boa!
tem como fazer o inverso?
como seria?
joao
27 \d\e agosto \d\e 2011
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…
nosklo
22 \d\e maio \d\e 2013