Friday, November 22, 2013

Errata for recent post ""Publish Microsoft Excel XLSX data to HTML with openpyxl"



By Vasudev Ram

Dear readers, while publishing my recent post,

Publish Microsoft Excel XLSX data to HTML with openpyxl, there were some errors in the HTML markup in the code listing, that had to do with missing or wrongly typed HTML entities, HTML elements, or quotes.

My apologies for the inconvenience caused.

I've now posted the corrected code below:

# XLSXtoHTML.py

# Program to convert the data from an XLSX file to HTML.
# Uses the openpyxl library.

# Author: Vasudev Ram - http://www.dancingbison.com

import openpyxl
from openpyxl import load_workbook

workbook = load_workbook('fruits.xlsx')
worksheet = workbook.get_active_sheet()

html_data = """
<html>
    <head>
        <title>
        XLSX to HTML demo
        </title>
    </head>
    <body>
        <h3>
        XLSX to HTML demo
        </h3>
        <table>
"""

ws_range = worksheet.range('A1:H13')
for row in ws_range:
    html_data += "<tr>"
    for cell in row:
        if cell.value is None:
            html_data += "<td>" + ' ' + "</td>"
        else:
            html_data += "<td>" + str(cell.value) + "</td>"
    html_data += "</tr>"
html_data += "</table></body></html>"

with open("fruits.html", "w") as html_fil:
    html_fil.write(html_data)

# EOF


- Vasudev Ram - Dancing Bison Enterprises



2 comments:

Anonymous said...

You can replace :
if cell.value is None:
html_data += "<td>" + ' ' + "</td>"
else:
html_data += "<td>" + str(cell.value) + "</td>"

by:
html_data += "<td>" + str(cell.value or '') + "</td>"

Vasudev Ram said...

Yes. But explicit is better than implicit, says The Zen Of Python.