一、概述
需求:使用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