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

如何通过Python脚本将.xlsx格式Excel表格转换为HTML网页?

批量将.xlsx文件转换为HTML网页的Python实现

1. 安装必要的Python库

需要用到pandas处理Excel数据,openpyxl作为.xlsx文件的读取引擎,执行以下命令安装:

pip install pandas openpyxl

2. 编写转换脚本

下面的脚本会遍历指定目录下的所有.xlsx文件,将每个文件转换为带基础样式的HTML页面:

import os
import pandas as pd

def xlsx_to_html(input_dir, output_dir=None):
    # 默认输出目录与输入目录一致
    if output_dir is None:
        output_dir = input_dir
    
    # 确保输出目录存在
    os.makedirs(output_dir, exist_ok=True)
    
    # 遍历目录下的.xlsx文件
    for filename in os.listdir(input_dir):
        if not filename.endswith('.xlsx'):
            continue
        
        xlsx_full_path = os.path.join(input_dir, filename)
        html_filename = f"{os.path.splitext(filename)[0]}.html"
        html_full_path = os.path.join(output_dir, html_filename)
        
        try:
            # 读取Excel第一个工作表
            df = pd.read_excel(xlsx_full_path, engine='openpyxl')
            # 生成表格HTML,隐藏行索引
            table_html = df.to_html(index=False, border=0)
            
            # 拼接完整HTML页面,添加基础样式
            full_html = f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{os.path.splitext(filename)[0]}</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 2rem; }}
        h1 {{ color: #333; }}
        table {{ width: 100%; border-collapse: collapse; margin-top: 1rem; }}
        th, td {{ padding: 0.8rem 1rem; text-align: left; border-bottom: 1px solid #eee; }}
        th {{ background-color: #f5f5f5; font-weight: 600; }}
        tr:hover {{ background-color: #f9f9f9; }}
    </style>
</head>
<body>
    <h1>{os.path.splitext(filename)[0]}</h1>
    {table_html}
</body>
</html>
            """
            
            # 写入HTML文件
            with open(html_full_path, 'w', encoding='utf-8') as f:
                f.write(full_html)
            
            print(f"转换完成:{filename} → {html_filename}")
        except Exception as e:
            print(f"转换{filename}失败:{str(e)}")

# 示例使用:替换为你的文件目录
if __name__ == '__main__':
    input_folder = './your_excel_files'  # 存放.xlsx的目录
    output_folder = './converted_html'   # 输出HTML的目录
    xlsx_to_html(input_folder, output_folder)

3. 脚本关键说明

  • 文件遍历:自动筛选目录下所有.xlsx后缀的文件,无需手动逐个处理
  • Excel读取:支持读取Excel默认第一个工作表,若需指定工作表,可给pd.read_excel添加sheet_name='指定表名'参数
  • 样式自定义:修改<style>标签内的CSS代码,可调整字体、颜色、间距等页面样式
  • 异常处理:单个文件转换失败不会中断整个脚本,方便批量处理时排查问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 05:10:05