和 C# 使用 Open XML SDK 2.5 輸出 Word 文件 這篇一樣,
先使用 NuGet 安裝 DocumentFormat.OpenXml 套件,或是使用 .NET CLI 執行以下指令安裝
讀取 Word 文件到 MemoryStream:
將兩個 MemoryStream 合併:
最後要將 MemoryStream 儲存成檔案也很簡單:
dotnet add package DocumentFormat.OpenXml --version 2.19.0
讀取 Word 文件到 MemoryStream:
public MemoryStream GetWordTemplate()
{
var filePath = GetWordTemplateFilePath();
using FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
MemoryStream memoryStream = new MemoryStream();
fileStream.CopyTo(memoryStream);
memoryStream.Position = 0;
return memoryStream;
}
將兩個 MemoryStream 合併:
public static MemoryStream MergeWordDocuments(this MemoryStream[] stream)
{
MemoryStream mergedStream = new MemoryStream();
using var myDoc = WordprocessingDocument.Create(mergedStream, WordprocessingDocumentType.Document, true);
MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
stream.ToList().ForEach(x =>
{
AppendDocumentToBody(x, body);
});
mergedStream.Position = 0;
return mergedStream;
}
private static void AppendDocumentToBody(MemoryStream stream, Body body)
{
using WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true);
var enumerable = wordDoc.MainDocumentPart?.Document.Body?.Elements();
if (enumerable == null) return;
foreach (var element in enumerable)
{
body.Append(element.CloneNode(true));
}
}
最後要將 MemoryStream 儲存成檔案也很簡單:
File.WriteAllBytes("my.docx", memoryStream.ToArray());
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com