Advertisement
ChrisProsser

write_html.py

Jun 28th, 2013
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.99 KB | None | 0 0
  1. !#/usr/bin/python
  2. import os, sys, traceback
  3.  
  4. def write_html_file(path, data, heads=None):
  5.     html = []
  6.     tab_attr = ' border="1" cellpadding="3" style="background-color:#FAFCFF; text-align:right"'
  7.     head_attr = ' style="background-color:#C0CFE2"'
  8.  
  9.     # opening lines needed for html table
  10.     try:
  11.         html.append('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ')
  12.         html.append('"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> ')
  13.         html.append('<html xmlns="http://www.w3.org/1999/xhtml">')
  14.         html.append('<body>')
  15.         html.append('  <table'+tab_attr+'>')
  16.     except:
  17.         print 'Error setting up html heading data'
  18.  
  19.     # html table headings (if required)
  20.     if heads:
  21.         try:
  22.             html.append('    <tr'+head_attr+'>')
  23.             for item in heads:
  24.                 html.append(' '*6+'<th>'+str(item)+'</th>')
  25.             html.append('    </tr>')
  26.         except:
  27.             exc_type, exc_value, exc_traceback = sys.exc_info()
  28.             lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
  29.             print 'Error writing html table headings:'
  30.             print ''.join('!! ' + line for line in lines)
  31.  
  32.     # html table content
  33.     try:
  34.         for row in data:
  35.             html.append('    <tr>')
  36.             for item in row:
  37.                 html.append(' '*6+'<td>'+str(item)+'</td>')
  38.             html.append('    </tr>')
  39.     except:
  40.         print 'Error writing body of html data'
  41.  
  42.     # closing lines needed
  43.     try:
  44.         html.append('  </table>')
  45.         html.append('</body>')
  46.         html.append('</html>')
  47.     except:
  48.         print 'Error closing html data'
  49.  
  50.     # write html data to file
  51.     fileout = open(path, 'w')
  52.     for line in html:
  53.         fileout.write(line)
  54.  
  55.     print 'Data written to:', path, '\n'
  56.  
  57.     if sql_path:
  58.         os.startfile(path)
  59.     else:
  60.         v_open = raw_input("Open file (Y/N):").upper()
  61.         if v_open == 'Y':
  62.             os.startfile(path)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement