IronWord 中 SaveAs 后页眉消失
SaveAs()作为标准的保存调用,且未报告页眉丢失问题。 请将此视为可能与特定环境相关的异常,而非已确认的产品缺陷,并在应用下面的解决方法之前在您自己的环境中进行验证。在某些环境中,当您使用IronWord填充DOCX模板并用SaveAs()写入结果时,模板的页眉可能会在生成的文件中消失,即使占位符合并正确。
Header (e.g. "City Attorney Cover Sheet") is visible in the original DOCX
but missing in the generated file after calling SaveAs().

在观察到此问题的环境中,使用Save()而非SaveAs()写入文档时,页眉得以保留。 这一点尚未在其他环境或IronWord的更新日志中得到证实——其他IronWord指南均将SaveAs()作为标准的保存调用,且不存在页眉丢失问题,因此请将此视为特定于环境的情况,而非已确认的产品缺陷。
解决方案
1. 加载模板
用WordDocument打开源DOCX。
using IronWord;
using System.Collections.Generic;
var templatePath = @"C:\Templates\CityAttorneyCoverSheetTemplate.docx";
var outputPath = @"C:\Output\merged.docx";
var doc = new WordDocument(templatePath);
using IronWord;
using System.Collections.Generic;
var templatePath = @"C:\Templates\CityAttorneyCoverSheetTemplate.docx";
var outputPath = @"C:\Output\merged.docx";
var doc = new WordDocument(templatePath);
Imports IronWord
Imports System.Collections.Generic
Dim templatePath As String = "C:\Templates\CityAttorneyCoverSheetTemplate.docx"
Dim outputPath As String = "C:\Output\merged.docx"
Dim doc As New WordDocument(templatePath)
2. 替换占位符
通过doc.Texts合并您的值,这是一种直接的查找/替换方法;对于使用MERGEFIELD语法、占位符较多的模板,IronWord还提供了专用的WordDocument.MailMerge API。
var replacements = new Dictionary<string, string>
{
["{CaseNumber}"] = "2026-CR-12345",
["{DefendantName}"] = "John Doe",
["{DefendantAge}"] = "34",
["{DefendantAttorney}"] = "Jane Smith",
};
foreach (var kv in replacements)
{
doc.Texts.ForEach(t => t.Replace(kv.Key, kv.Value));
}
var replacements = new Dictionary<string, string>
{
["{CaseNumber}"] = "2026-CR-12345",
["{DefendantName}"] = "John Doe",
["{DefendantAge}"] = "34",
["{DefendantAttorney}"] = "Jane Smith",
};
foreach (var kv in replacements)
{
doc.Texts.ForEach(t => t.Replace(kv.Key, kv.Value));
}
Imports System.Collections.Generic
Dim replacements As New Dictionary(Of String, String) From {
{"{CaseNumber}", "2026-CR-12345"},
{"{DefendantName}", "John Doe"},
{"{DefendantAge}", "34"},
{"{DefendantAttorney}", "Jane Smith"}
}
For Each kv In replacements
doc.Texts.ForEach(Sub(t) t.Replace(kv.Key, kv.Value))
Next
遍历doc.Texts中的每个条目,将文档主体中的每个占位符标记替换为其合并值。
3. 用 Save() 保存,而不是 SaveAs()
用doc.Save(outputPath)写入输出。 这保持了页眉的完整,而doc.SaveAs(outputPath)可能会丢失页眉。
doc.Save(outputPath);
doc.Save(outputPath);
doc.Save(outputPath)

注意事项
- 如果您的工作流程需要
SaveAs():请在最新的IronWord版本上验证您的环境中页眉是否得以保留。 - 如果问题重新出现: 固定到之前工作的版本作为短期缓解措施,同时调查该行为。

