2014-09-24 171 views
0
import sqlite3,os 
db=r'F:\workspace\china\data\china.sqlite' 
con=sqlite3.connect(db) 
cur=con.cursor() 
res=cur.execute('select 代碼,所屬行業,註冊資本,僱員人數,管理人員人數 from profile limit 20').fetchall() 
for row in res: 
    print(row) 

('600000', '銀行', '187億', 39340.0, 30.0)
('600004', '民航機場', '11.5億', 4499.0, 23.0)
('600005', '鋼鐵行業', '101億', 38857.0, 24.0)
('600006', '汽車行業', '20.0億', 10290.0, 20.0)
('600007', '房地產', '10.1億', 2332.0, 19.0)
('600008', '公用事業', '22.0億', 6515.0, 20.0)
('600009', '民航機場', '19.3億', 5472.0, 18.0)
('600010', '鋼鐵行業', '80.0億', 31389.0, 19.0)
('600011', '電力行業', '141億', 37729.0, 29.0)
('600012', '高速公路', '16.6億', 2106.0, 14.0)
('600015', '銀行', '89.0億', 25200.0, 34.0)
('600016', '銀行', '340億', 54927.0, 32.0)
('600017', '港口水運', '30.8億', 5340.0, 21.0)
('600018', '港口水運', '228億', 19842.0, 20.0)
('600019', '鋼鐵行業', '165億', 37487.0, 23.0)
('600020', '高速公路', '22.5億', 2959.0, 32.0)
('600021', '電力行業', '21.4億', 6673.0, 22.0)
('600022', '鋼鐵行業', '64.4億', 31738.0, 20.0)
('600023', '電力行業', '118億', 10142.0, 14.0)
('600026', '港口水運', '34.0億', 7536.0, 21.0)How to display the result with temple jinjia2 or others?

Now i want to display the output in html table.

html_str='<table border=1>' 
for row in res: 
    html_str=html_str+'<tr>' 
    for col in row: 
     html_str=html_str+'<td>'+str(col) 
     html_str=html_str+'</td>' 
    html_str=html_str+'</tr>' 

html_str=html_str+'</table>' 
myhtml=open('f:\\test.html','w') 
myhtml.write(html_str) 
myhtml.close() 
os.system('"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" f:\\test.html') 

I want to improve my code
1.to simplify the creation of html file.
2.it is stupid to open the test.html file with
os.system('"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" f:\\test.html')

How can i display it with temple jinjia2 more elegantly?

回答

0

Make a template with jinja2.Template :

import jinja2 

template = jinja2.Template(''' 
<table border=1> 
{% for row in res %} 
    <tr> 
    {% for col in row -%} 
     <td>{{ col|replace('\s', ':1,7>') }}</td> 
    {% endfor %} 
    </tr> 
{% endfor %} 
</table> 
''') 

Render the template with jinja2.Template.render (with res passed), then write it to file:

with open('test.html', 'w') as f: 
    f.write(template.render(res=res)) 

To open the file in browser, use webbrowser.open (It will use the default web browser):

import webbrowser 
webbrowser.open('test.html')