pandas实现excel转为html格式并设置css样式

本文介绍如何使用pandas将Excel文件转换为HTML格式,并通过自定义CSS样式美化表格展示。此外,还提供了处理多页签Excel文件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、概述

需求:使用pandas读取excel,并生成html文件

二、演示

import pandas as pd
import codecs
xd = pd.ExcelFile('456.xlsx')
df = xd.parse()
with codecs.open('1.html','w','utf-8') as html_file:
    html_file.write(df.to_html(header = True,index = False))

执行程序,使用浏览器打开1.html,效果如下:

默认样式,可能不太好看,可以自定义css

新建文件df_style.css,内容如下:

/* includes alternating gray and white with on-hover color */
.mystyle {
    font-size: 11pt;
    font-family: Arial;
    border-collapse: collapse;
    border: 1px solid silver;
}
.mystyle td, th {
    padding: 5px;
}
.mystyle tr:nth-child(even) {
    background: #E0E0E0;
}
.mystyle tr:hover {
    background: silver;
    cursor: pointer;
}

应用css文件

import pandas as pd
import codecs
pd.set_option('display.width', 1000)
pd.set_option('colheader_justify', 'center')
xd = pd.ExcelFile('456.xlsx')
df = xd.parse()
# with codecs.open('1.html','w','utf-8') as html_file:
#     html_file.write(df.to_html(header = True,index = False))

pd.set_option('colheader_justify', 'center')   # FOR TABLE <th>
html_string = '''
<html>
  <head><title>HTML Pandas Dataframe with CSS</title></head>
  <link rel="stylesheet" type="text/css" href="df_style.css"/>
  <body>
    {table}
  </body>
</html>.
'''
# OUTPUT AN HTML FILE
with open('myhtml.html',encoding='utf-8',mode='w') as f:
    f.write(html_string.format(table=df.to_html(classes='mystyle')))

执行程序,使用浏览器打开myhtml.html,效果如下:

上面只是读取了一个sheet,如果要读取多个sheet呢?

修改一下代码

import os
import pandas as pd
import codecs
pd.set_option('display.width', 1000)
pd.set_option('colheader_justify', 'center')
excel_file = '456.xlsx'
xd = pd.ExcelFile(excel_file)

# 遍历每一个sheet
for i in xd.sheet_names:
    # print(i,type(i))
    # 读取指定sheet
    df = xd.parse(sheet_name=i)

    pd.set_option('colheader_justify', 'center')   # FOR TABLE <th>
    html_string = '''
    <html>
      <head><title>HTML Pandas Dataframe with CSS</title></head>
      <link rel="stylesheet" type="text/css" href="df_style.css"/>
      <body>
        {table}
      </body>
    </html>.
    '''

    # OUTPUT AN HTML FILE
    # 创建excel文件夹,用来存放sheet文件
    sheet_dir = excel_file.split('.')[0]
    # print("sheet_dir",sheet_dir)
    if not os.path.exists(sheet_dir):
        os.mkdir(sheet_dir)

    # 写入sheet文件
    sheet_file = os.path.join(sheet_dir, i + '.html')

    with open(sheet_file,encoding='utf-8',mode='w') as f:
        f.write(html_string.format(table=df.to_html(classes='mystyle')))

执行代码,它会创建和excel文件同名的目录,进入目录,会有3个html文件

打开Sheet1.html,效果同上!

本文参考链接:

https://blog.youkuaiyun.com/wangxingfan316/article/details/79609711

https://blog.youkuaiyun.com/qq_38316655/article/details/104663077

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值