美文网首页
python实现Excel文件转Html

python实现Excel文件转Html

作者: 忘了呼吸的那只猫 | 来源:发表于2021-12-03 16:48 被阅读0次

    因为有一个Excel文件在线预览的需求,我尝试将Excel文件转换成PDF,但效果不怎么好,所以突发奇想使用pandas库中的to_html方法,将Excel文件中的数据抽取出来,生成table表格

    安装pandas

    pip install pandas
    

    卸载掉xlrd

    pip uninstall xlrd
    

    安装低版本的

    pip install xlrd==1.2.0
    

    卸载的原因是因为,使用pandas打开excel文件的时候依赖xlrd库,但是高版本的已经不支持打开xslx格式的文档了
    准备完毕上代码:

    #!/usr/bin/env Python
    # coding=utf-8
    import pandas as pd
    import codecs
    xd = pd.ExcelFile('123test.xlsx')
    df = xd.parse()
    html_str = df.to_html(header = True,index = False, col_space=100)
    style = '''
    <style>
        table{
            border-spacing:0;  
        }
        th{
            text-align:center;vertical-align:middle;
        }
        td{
            text-align:center;vertical-align:middle;
        }
    </style>
    '''
    html_str = style + html_str
    with codecs.open('123test.html','w','utf-8') as html_file:
         html_file.write(html_str)
    

    如果需要加点更炫酷的样式也可以在style中添加

    相关文章

      网友评论

          本文标题:python实现Excel文件转Html

          本文链接:https://www.haomeiwen.com/subject/vuqmxrtx.html