You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自动创建HTML文件并批量插入Excel数据?

基于Excel数据批量生成古典作曲家静态HTML页面的Python实现

前置准备

  1. 安装依赖库:

    pip install pandas openpyxl
    

    (openpyxl是pandas读取xlsx格式文件的依赖,通常默认已安装)

  2. 准备HTML模板文件(命名为template.html),用{{占位符}}标记需要替换的动态内容,示例如下:

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>{{Name}} - 古典作曲家</title>
        <style>
            .container {
                max-width: 900px;
                margin: 30px auto;
                padding: 20px;
                font-family: serif;
            }
            .portrait {
                width: 220px;
                float: left;
                margin-right: 25px;
                border-radius: 6px;
            }
            h1 {
                border-bottom: 1px solid #ccc;
                padding-bottom: 10px;
            }
            .work-section {
                margin-top: 30px;
                clear: both;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>{{Name}}</h1>
            <img src="{{Picture}}" alt="{{Name}} 肖像" class="portrait">
            <div class="bio">
                <h2>作曲家简介</h2>
                <p>{{Description}}</p>
            </div>
            <div class="work-section">
                <h2>代表作品</h2>
                <p>{{Piece}}</p>
            </div>
        </div>
    </body>
    </html>
    

核心代码

创建Python脚本(比如generate_html.py),代码如下:

import pandas as pd
import os

# 配置文件路径,根据你的实际情况修改
EXCEL_FILE = "composers.xlsx"
TEMPLATE_FILE = "template.html"
OUTPUT_FOLDER = "composer_htmls"

# 创建输出文件夹,不存在则自动生成
os.makedirs(OUTPUT_FOLDER, exist_ok=True)

# 读取Excel数据,确保列名严格匹配:Picture、Name、Description、Piece
df = pd.read_excel(EXCEL_FILE)

# 读取HTML模板内容
with open(TEMPLATE_FILE, "r", encoding="utf-8") as f:
    template = f.read()

# 遍历每一行数据生成HTML文件
for _, row in df.iterrows():
    # 替换模板中的占位符,同时处理空值情况
    name = str(row["Name"]) if pd.notna(row["Name"]) else "未知作曲家"
    pic_path = str(row["Picture"]) if pd.notna(row["Picture"]) else "images/default.png"
    desc = str(row["Description"]) if pd.notna(row["Description"]) else "暂无相关简介"
    works = str(row["Piece"]) if pd.notna(row["Piece"]) else "暂无记录代表作品"

    final_html = template.replace("{{Name}}", name)\
                        .replace("{{Picture}}", pic_path)\
                        .replace("{{Description}}", desc)\
                        .replace("{{Piece}}", works)
    
    # 生成安全的文件名(避免特殊字符导致路径错误)
    safe_filename = name.replace("/", "_").replace("\\", "_").replace(":", "_") + ".html"
    output_path = os.path.join(OUTPUT_FOLDER, safe_filename)

    # 写入文件
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(final_html)
    
    print(f"已生成: {output_path}")

print("所有页面生成完成!")

使用说明

  1. 将你的Excel文件命名为composers.xlsx,确保列名严格匹配:Picture(图片路径,建议用相对路径,比如images/beethoven.jpg)、Name(作曲家姓名)、Description(简介)、Piece(代表作品)
  2. 把HTML模板和Excel文件放在和Python脚本同一目录下
  3. 运行脚本:python generate_html.py,生成的HTML文件会自动存入composer_htmls文件夹

可选优化

  • 如果需要手动创建HTML文件再插入数据,可以修改代码,读取已有的HTML文件列表,按文件名匹配Excel中的姓名进行替换(但批量生成更高效)
  • 可以给模板添加更多样式,适配古典主题的网站风格

内容的提问来源于stack exchange,提问作者rawru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 18:35:26