批量将 Word 文件转换为 HTML:Python 实现指南

[复制链接]
发表于 2024-12-25 20:31:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
概述

在日常工作中,我们大概会遇到将大量 Word 文档(.docx)转换为 HTML 文件的需求,比如为了将文档内容展示到网页上,大概实现文档在线阅读功能。今天,我们将分享一个用 Python 编写的实用工具,支持将整个文件夹下的 Word 文件批量转换为 HTML,同时保存文档的样式,如段落缩进、加粗、斜体等。
工具功能

支持单个 Word 文件到 HTML 的转换。
批量处理文件夹中的 Word 文件。
保存段落样式(如段落缩进、首行缩进、左右边距等)。
支持加粗、斜体、下划线等文本样式。
支持 Word 文档中的表格内容转换。
实当代码

以下是完整的实当代码
  1. import os
  2. from docx import Document
  3. from html import escape
  4. def docx_to_html(docx_path):
  5.     """将单个 Word 文件转换为 HTML,保留换行、段落、缩进等格式"""
  6.     document = Document(docx_path)
  7.     html_content = "<html><head><meta charset='utf-8'></head><body>"
  8.     for paragraph in document.paragraphs:
  9.         # 获取段落的样式
  10.         left_indent = paragraph.paragraph_format.left_indent
  11.         right_indent = paragraph.paragraph_format.right_indent
  12.         first_line_indent = paragraph.paragraph_format.first_line_indent
  13.         # 样式转换为 HTML 的 inline 样式
  14.         styles = []
  15.         if left_indent:
  16.             styles.append(f"margin-left: {int(left_indent.pt * 1.33)}px;")
  17.         if right_indent:
  18.             styles.append(f"margin-right: {int(right_indent.pt * 1.33)}px;")
  19.         if first_line_indent:
  20.             styles.append(f"text-indent: {int(first_line_indent.pt * 1.33)}px;")
  21.         style_attribute = f" style='{' '.join(styles)}'" if styles else ""
  22.         # 转换加粗、斜体等样式
  23.         content = ""
  24.         for run in paragraph.runs:
  25.             run_text = escape(run.text)
  26.             if run.bold:
  27.                 run_text = f"<b>{run_text}</b>"
  28.             if run.italic:
  29.                 run_text = f"<i>{run_text}</i>"
  30.             if run.underline:
  31.                 run_text = f"<u>{run_text}</u>"
  32.             content += run_text
  33.         # 包裹为段落
  34.         html_content += f"<p{style_attribute}>{content}</p>"
  35.     # 处理表格
  36.     for table in document.tables:
  37.         html_content += "<table border='1' style='border-collapse: collapse; width: 100%;'>"
  38.         for row in table.rows:
  39.             html_content += "<tr>"
  40.             for cell in row.cells:
  41.                 html_content += f"<td>{escape(cell.text)}</td>"
  42.             html_content += "</tr>"
  43.         html_content += "</table>"
  44.     html_content += "</body></html>"
  45.     return html_content
  46. def batch_convert_to_html(input_folder, output_folder):
  47.     """批量将文件夹下的 docx 文档转换为 HTML 文件"""
  48.     if not os.path.exists(output_folder):
  49.         os.makedirs(output_folder)
  50.     for filename in os.listdir(input_folder):
  51.         if filename.endswith(".docx"):
  52.             input_path = os.path.join(input_folder, filename)
  53.             output_path = os.path.join(output_folder, f"{os.path.splitext(filename)[0]}.html")
  54.             try:
  55.                 html_content = docx_to_html(input_path)
  56.                 with open(output_path, 'w', encoding='utf-8') as html_file:
  57.                     html_file.write(html_content)
  58.                 print(f"成功转换: {filename} -> {output_path}")
  59.             except Exception as e:
  60.                 print(f"转换失败: {filename}, 错误信息: {e}")
  61. # 设置输入和输出文件夹路径
  62. input_folder = r"input_path"  # 替换为存储 Word 文档的文件夹路径
  63. output_folder = r"output_path"  # 替换为存储 HTML 文件的文件夹路径
  64. # 批量转换
  65. batch_convert_to_html(input_folder, output_folder)
复制代码
代码剖析

1. docx_to_html 函数



  • 功能:将单个 Word 文件转换为 HTML。
  • 剖析段落样式:
    – 使用 paragraph_format 获取段落的左缩进、右缩进和首行缩进。
    – 转换为 HTML 的内联样式。
    – 转换文本样式:
    – 剖析 run 对象的加粗、斜体和下划线样式,生成对应的 HTML 标签。
  • 处理表格:
    – 将 Word 表格转换为带边框的 HTML 表格。
2. batch_convert_to_html 函数



  • 功能:批量处理文件夹下的 Word 文件。
  • 主动创建输出文件夹。
  • 遍历输入文件夹下的 .docx 文件,并逐个调用 docx_to_html 函数。
  • 将生成的 HTML 文件存储到输出文件夹。
3. 主程序



  • 设置输入文件夹和输出文件夹路径。
  • 调用 batch_convert_to_html 完成批量转换。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告
回复

使用道具 举报

© 2001-2025 Discuz! Team. Powered by Discuz! X3.5

GMT+8, 2025-7-3 03:52 , Processed in 0.274360 second(s), 32 queries 手机版|qidao123.com技术社区-IT企服评测▪应用市场 ( 浙ICP备20004199 )|网站地图

快速回复 返回顶部 返回列表