将python list数据结果存为html

如果想让list数据直接展示为html表格,可以用pandas.to_html()。

这里主要涉及到可以改变表格内的数据样式,如果想将数据的某个字词进行样式改变,可以直接在list中的数据上加html标签,如<span style="color:red">等。

html1 = """<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"></head>
<body>
  <table border='1' width='400'>
  
    <tr>
        <th>index</th>
        <th>l1</th>
        <th>l2</th>
        <th>l3</th>
        <th>l4</th>
    </tr>
"""

html2 = """
    <tr>
        <td>%d</td>
        <td>%s</td>
        <td>%s</td>
        <td>%s</td>
        <td>%s</td>
    <tr>
"""

html3 = """
      </table>
</body>
</html>
"""

l = [[1, 'a', 'b','c', 'd'], [2, 'A', 'B','C', 'D'], [3, '<span style="color:red">aa</span>', 'bb','cc', 'dd']]
tf = open('ttmp.html', 'w', encoding='utf-8')
tf.write(html1)
for i in range(len(l)):
    tf.write(html2%(tuple(l[i])))
tf.write(html3)
tf.close()

结果展示:

posted @ 2021-08-16 16:47  ho_ho  阅读(700)  评论(0编辑  收藏  举报