1. 程式人生 > 其它 >pandas實現excel轉為html格式並設定css樣式

pandas實現excel轉為html格式並設定css樣式

技術標籤:csspythonexcelhtmljava

一、概述

需求:使用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.csdn.net/wangxingfan316/article/details/79609711

https://blog.csdn.net/qq_38316655/article/details/104663077