Python excel转成html页面 excel 在线预览
因为这两天公司的项目要用到在浏览excel 所以就在做这个功能。一开始查了很多资料 都是各种不行,最后好不容易找到一些辅助资料 终于是今天把它修改完成了,用的是dominate生成静态页面的方法。(还有其他方法的) 有需要的拿去用吧 下面贴上代码:
import logging,dominate, openpyxl, sys, os
from xlrd import open_workbook
from dominate.tags import *
# 创建获取excel数据的函数
def excel_sheet_processor(filepath):
# 通过open_workbook函数 获取Book对象
wb = open_workbook(filepath, formatting_info=True)
# 创建一个新的sheet 对象
ws = wb.sheet_by_index(0)
# 创建2个空列表用于储存数据
workbook_list = []
my_keys = []
# 通过遍历ncols 获取excel表中第一行(python中0是第一行的意思)和所有列的数据
for col in range(ws.ncols):
my_keys.append(ws.cell_value(rowx=0, colx=col))
# 通过遍历nrows和 获取excel表中所有行里面的和对应列的数据
for r in range(1,ws.nrows):
dict = {}
for pos in range(0, len(my_keys)):
dict[my_keys[pos]] = ws.cell_value(rowx=r, colx=pos)
# 将获取的字典数据 添加进一开始写好的空列表中
workbook_list.append(dict)
return workbook_list
# 创建excel生成静态html页面的函数
def list_diction_to_html(list_work):
# 用dominate函数生成静态html页面
doc = dominate.document(title='excel-to-html')
# 写在头部的 css 可以自定义自己的想要用的css文件, (重要: meta一定要加 要不会在打开html时乱码,因为html默认不是utf-8编码)
with doc.head:
link(rel='stylesheet', href='Perconnel/static/css/style.css')
meta(charset='utf-8')
# 创建一个table,将获取到的数据通过遍历添加进去对应的位置
with doc:
with div(id='excel_table').add(table()):
with thead():
dict = list_work[0]
for key in dict.keys():
table_header = td()
table_header.add(p(key))
for dict2 in list_work:
table_row = tr(cls='excel_table_row')
for key in dict2:
with table_row.add(td()):
p(dict2[key])
return str(doc)
# 保存生成后html的函数
def save_dom_to_html(dom):
filepath = os.path.abspath("excel.html")
htmfile = open(filepath, "w")
htmfile.write(dom)
htmfile.close()
return filepath
# 文件地址可以通过数据库里存的获取, 此用于测试 所以写了绝对路径
if __name__ == '__main__':
filepath = os.path.abspath('Personnel/media/upload/001.xls')
list_work = excel_sheet_processor(filepath)
if list_work:
dom = list_diction_to_html(list_work)
save_dom_to_html(dom)
做为一个初级程序员 ,更多的是希望获取更多的正确的功能代码,希望大家在留下功能代码的时候 多留下注释,要不浏览起来 真的太难了- -!
有疑问的欢迎留言,看到会及时回复。
或者可以添加我V :583193164问我。~
祝大家新的一年 身体健康 心想事成!!!
更多推荐
Python excel转成html页面 excel 在线预览
发布评论