因此,我尝试通过匹配标签并在该内容控件中填充文本来填充 word 文档中的内容控件。
以下在 MessageBox 中显示我文档中的所有标签。
//Create a copy of the template file and open the document
File.Delete(hhscDocument);
File.Copy(hhscTemplate, hhscDocument, true);
//Open the word document specified by location
using (var document = WordprocessingDocument.Open(hhscDocument, true))
{
//Change the document type from template to document
var mainDocument = document.MainDocumentPart.Document;
if (mainDocument.Body.Descendants<Tag>().Any())
{
//MessageBox.Show(mainDocument.Body.Descendants<Table>().Count().ToString());
var tags = mainDocument.Body.Descendants<Tag>().ToList();
var aString = string.Empty;
foreach(var tag in tags)
{
aString += string.Format("{0}{1}", tag.Val, Environment.NewLine);
}
MessageBox.Show(aString);
}
}
但是,当我尝试以下操作时,它不起作用。
//Create a copy of the template file and open the document
File.Delete(hhscDocument);
File.Copy(hhscTemplate, hhscDocument, true);
//Open the word document specified by location
using (var document = WordprocessingDocument.Open(hhscDocument, true))
{
//Change the document type from template to document
var mainDocument = document.MainDocumentPart.Document;
if (mainDocument.Body.Descendants<Tag>().Any())
{
//MessageBox.Show(mainDocument.Body.Descendants<Table>().Count().ToString());
var tags = mainDocument.Body.Descendants<Tag>().ToList();
var bString = string.Empty;
foreach(var tag in tags)
{
bString += string.Format("{0}{1}", tag.Parent.GetFirstChild<Text>().Text, Environment.NewLine);
}
MessageBox.Show(bString);
}
}
我最终的目标是,如果我匹配了我想要填充/更改该标签所属的内容控件中的文本的适当标签。
最佳答案
所以我基本上使用 FirstChild 和 InnerXml 来分离文档 XML 内容。从那里我开发了以下满足我需要的东西。
//Open the word document specified by location
using (var document = WordprocessingDocument.Open(hhscDocument, true))
{
var mainDocument = document.MainDocumentPart.Document;
if (mainDocument.Body.Descendants<Tag>().Any())
{
//Find all elements(descendants) of type tag
var tags = mainDocument.Body.Descendants<Tag>().ToList();
//Foreach of these tags
foreach (var tag in tags)
{
//Jump up two levels (.Parent.Parent) in the XML element and then jump down to the run level
var run = tag.Parent.Parent.Descendants<Run>().ToList();
//I access the 1st element because there is only one element in run
run[0].GetFirstChild<Text>().Text = "<new_text_value>";
}
}
mainDocument.Save();
}
这会找到文档中的所有标签并将元素存储在列表中
var tags = mainDocument.Body.Descendants<Tag>().ToList();
这部分代码从 xml 的标记部分开始。从那里我两次调用 parent 以在 XML 代码中向上跳转两个级别,这样我就可以使用后代访问 Run 级别。
var run = tag.Parent.Parent.Descendants<Run>().ToList();
最后但同样重要的是,以下代码将新值存储到 PlainText Content 控件的文本部分。
run[0].GetFirstChild<Text>().Text = "<new_text_value>";
我注意到的是 xml 层次结构是一个时髦的东西。我发现自下而上访问这些内容更容易,因此我从标签开始并向上移动。
关于c# - 使用 OpenXML 和 C# 处理 word 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32077505/