HTML导出Word文档时保留1.5倍行距的解决方案

HTML导出Word文档时保留1.5倍行距的解决方案

问题背景

在将HTML内容导出为Word文档时,开发者常遇到行间距设置失效的问题。即使CSS中设置了line-height: 1.5150%,生成的Word文档仍会默认使用单倍行距,严重影响文档可读性和专业排版效果。


核心原因分析

Word对CSS的支持存在以下局限:

  1. 部分CSS属性不兼容:Word仅支持有限的CSS属性集
  2. 行高计算差异:Word使用独特的行高计算规则
  3. 默认样式覆盖:Word会强制应用其内置样式表

解决方案

使用Word专用CSS属性

1
2
3
4
5
6
7
p {
line-height: 150%; /* 标准浏览器行高设置 */
mso-line-height-rule: exactly; /* Word专用行高规则 */
text-indent: 2em; /* 首行缩进2字符 */
margin-bottom: 15px; /* 段后间距 */
text-align: justify; /* 两端对齐 */
}

关键实现要点

  1. 双属性配合使用

    • line-height: 150% 确保在浏览器中正常显示
    • mso-line-height-rule: exactly 强制Word精确应用行高值
  2. mso专属属性说明

    • mso-line-height-rule 是Microsoft Office专用CSS属性
    • exactly 参数确保行高值被严格遵循
    • 兼容Word 2007及以上版本
  3. 最佳实践组合

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    /* 推荐全局样式 */
    body {
    mso-line-height-rule: exactly;
    line-height: 1.5;
    font-family: "微软雅黑", "Microsoft YaHei";
    }

    /* 标题特殊处理 */
    h1, h2, h3 {
    mso-line-height-rule: at-least;
    line-height: 2.0;
    }

完整实现示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
<head>
<style>
/* 核心行距解决方案 */
.word-export {
line-height: 150%;
mso-line-height-rule: exactly;
text-indent: 2em;
}

/* 其他优化样式 */
.word-export p {
margin-bottom: 15px;
text-align: justify;
}

.word-export table {
mso-displayed-decimal-separator: "\.";
mso-displayed-thousand-separator: "\,";
}
</style>
</head>
<body class="word-export">
<h1>文档标题</h1>
<p>这里是1.5倍行距的正文内容,导出到Word时将完美保持行间距格式...</p>
</body>
</html>


HTML导出Word文档时保留1.5倍行距的解决方案
https://kymi1723.github.io/2025/06/13/html-export-to-word-keep-1-5-line-spacing/
作者
kymi
发布于
2025年6月14日
许可协议