根据设置的excel格式和预置的html模板,批量生成新的html页面

本文介绍如何利用Python结合Excel数据和预设HTML模板,自动化批量生成符合特定格式要求的HTML文件,适用于数据报告或网页制作场景。
import os,time,shutil,re,copy
import pandas as pd 
import numpy as np  

root_path=os.path.dirname(__file__)
output_path=os.path.join(root_path,'output',time.strftime('%Y%m%d'))
os.makedirs(output_path,exist_ok=True)
output_config_files_path=os.path.join(output_path,'config.files')
if os.path.exists(output_config_files_path):
	shutil.rmtree(output_config_files_path)
shutil.copytree(
	os.path.join(root_path,'config.files'),
	output_config_files_path
	)
# 获取html模板
with open(os.path.join(root_path,'config.files','sheet001.htm'),'r',encoding='utf8') as f:
	html_lines=f.readlines()
blocks_dicts={}
pattern=r'<!-- block_(.*?) -->'
pattern_end=r'<!-- block_(.*?) end -->'
for i,line in enumerate(html_lines):
	result=re.search(pattern,line)
	if result:
		if 'end' not in line:
			blcok_name=result.group(1)
			blocks_dicts[blcok_name]=[i,0]
		else:
			blocks_dicts[blcok_name][1]=i
print(blocks_dicts)

df=pd.read_excel(os.path.join(root_path,'config.xlsx'))
for row in range(df.shape[0]):
	new_html_lines=copy.deepcopy(html_lines)
	# print(df.iloc[row])
	for line_i in range(*blocks_dicts['sp']):
		new_html_lines[line_i]=html_lines[line_i].replace("{__{sp}__}",df.loc[row,'sp'])

	trs_list=[]	
	for i,item in enumerate(df.loc[row,'项目1'].split()):
		tr_list=copy.deepcopy( html_lines[blocks_dicts['tr'][0]+1:blocks_dicts['tr'][1]])
		for sub_i,line in enumerate(tr_list):
			if '项目1' in line:
				tr_list[sub_i]=line.replace("{__{项目1}__}",df.loc[row,'项目1'].split()[i])
			elif '项目2' in line:
				tr_list[sub_i]=line.replace("{__{项目2}__}",df.loc[row,'项目2'].split()[i])
			elif '项目3' in line:
				tr_list[sub_i]=line.replace("{__{项目3}__}",df.loc[row,'项目3'].split()[i])
			elif '项目4' in line:
				tr_list[sub_i]=line.replace("{__{项目4}__}",df.loc[row,'项目4'].split()[i])
			
		# trs_list=[*trs_list,*tr_list]
		trs_list += tr_list
		print(item)

	new_html_lines=[
		*new_html_lines[:blocks_dicts['tr'][0]+1],
		*trs_list,
		*new_html_lines[blocks_dicts['tr'][1]:],
	]
	with open(os.path.join(output_config_files_path,df.loc[row,'sp']+'.html'),'w',encoding='utf8') as f:
		f.writelines(new_html_lines)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值