【发布时间】:2017-08-09 05:04:07
【问题描述】:
我正在尝试连接到 Microsoft Word 文档 (.docx) 以从位于 .docx 中的表中读取值。我正在使用 Open-XML SDK 2.0 连接到 .docx 文件。到目前为止,在寻找示例和想法之后,我有了这个,
public static string TextFromWord(string file)
{
const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
StringBuilder textBuilder = new StringBuilder();
using (WordprocessingDocument wDoc = WordprocessingDocument.Open(filename,false))
{
//Manage namespaces to perform Xpath queries
NameTable nt = new NameTable();
XmlNamespaceManager nsManger = new XmlNamespaceManger(nt);
nsManager.AddNamespace("w", wordmlNamespace);
//Get the document part from the package.
//Load the XML in the document part into an XmlDocument instance.
XmlDocument xdoc = new XmlDocument(nt);
xdoc.Load(wdDoc.MainDocumentPart.GetStream());
XmlNodeList paragraphNodes = xdoc.SelectNodes("//w:p", nsManager);
foreach (XmlNode paragraphNode in paragraphNodes)
{
XmlNodeList textNodes = paragraphNode.SelectNodes(".//w:t", nsmanager);
foreach (System.Xml.XmlNode textNode in textNodes)
{
textBuilder.Append(textNode.InnerText);
}
textBuilder.Append(Environment.NewLine);
}
}
return textBuilder.ToString();
}
当 .docx 中只有文本时代码有效,但当文本在表格中时代码失败。有没有办法解决这个问题,以便它可以与 .docx 中的表格一起使用?
【问题讨论】:
标签: c# openxml-sdk