![](/img/trans.png)
[英]Fill in Word template and save as pdf using openxml and openoffice
[英]Fill word template data using openXML SDK
我有一個用於數據的 word 文件模板和 xml 文件。 我想在 word 中找到 content 內容控件並從 xml 中獲取數據,然后替換 word 模板中的文本。 我正在使用以下代碼,但它沒有更新 word 文件。
using (WordprocessingDocument document = WordprocessingDocument.CreateFromTemplate(txtWordFile.Text))
{
MainDocumentPart mainPart = document.MainDocumentPart;
IEnumerable<SdtBlock> block = mainPart.Document.Body.Descendants<SdtBlock>().Where
(r => r.SdtProperties.GetFirstChild<Tag>().Val == "TotalClose");
Text t = block.Descendants<Text>().Single();
t.Text = "13,450,542";
mainPart.Document.Save();
}
對於仍在為此苦苦掙扎的任何人 - 您可以查看此庫https://github.com/antonmihaylov/OpenXmlTemplates
有了它,您可以替換基於 JSON 對象(或基本 C# 字典)的文檔所有內容控件中的文本,而無需編寫特定代碼,而是在內容控件的標簽中指定變量名稱。
(注意 - 我是該庫的制造商,但它是開源的,並在 LGPLv3 下獲得許可)
我認為您應該將更改寫入臨時文件。 請參閱將修改后的 WordprocessingDocument 保存到新文件或我的工作項目代碼:
MemoryStream yourDocStream = new MemoryStream();
... // populate yourDocStream with .docx bytes
using (Package package = Package.Open(yourDocStream, FileMode.Open, FileAccess.ReadWrite))
{
// Load the document XML in the part into an XDocument instance.
PackagePart packagePart = LoadXmlPackagePart(package);
XDocument xDocument = XDocument.Load(XmlReader.Create(packagePart.GetStream()));
// making changes
// Save the XML into the package
using (XmlWriter xw = XmlWriter.Create(packagePart.GetStream(FileMode.Create, FileAccess.Write)))
{
xDocument.Save(xw);
}
var resultDocumentBytes = yourDocStream.ToArray();
}
您使用的基本方法工作正常,但我很驚訝您沒有收到任何編譯時錯誤,因為
IEnumerable<SdtBlock> block = mainPart.Document
.Body
.Descendants<SdtBlock>()
.Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "TotalClose");
不兼容
Text t = block.Descendants<Text>().Single();
block
,因為IEnumerable
沒有Descendants
屬性。 您要么需要遍歷IEnumerable
所有項目並對每個項目執行此操作,要么您需要定義和實例化單個項目,如下所示:
using (WordprocessingDocument document = WordprocessingDocument.CreateFromTemplate(txtWordFile.Text))
{
MainDocumentPart mainPart = pkgDoc.MainDocumentPart;
SdtBlock block = mainPart.Document.Body.Descendants<SdtBlock>().Where
(r => r.SdtProperties.GetFirstChild<Tag>().Val == "test1").FirstOrDefault();
Text t = block.Descendants<Text>().Single();
t.Text = "13,450,542";
mainPart.Document.Save();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.