在 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);Imports IronWord
Imports System.Collections.Generic
Dim templatePath = "C:\Templates\CityAttorneyCoverSheetTemplate.docx"
Dim outputPath = "C:\Output\merged.docx"
Dim doc = New WordDocument(templatePath)Imports IronWord
Imports System.Collections.Generic
Dim templatePath = "C:\Templates\CityAttorneyCoverSheetTemplate.docx"
Dim outputPath = "C:\Output\merged.docx"
Dim doc = 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));
}Dim replacements = 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))
NextDim replacements = 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)doc.Save(outputPath)
注意事項
- 如果您的工作流程需要
SaveAs(): 請使用最新版 IronWord,在您的環境中確認頁首是否仍會保留。 - 如果問題再次出現: 在調查此行為期間,將版本固定為先前可正常運作的版本,作為短期因應措施。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。