简体   繁体   English

无法以MS Word读取openXML表

[英]openXML tables not being read in MS word

I'm trying to read all the tables from a word file into a list, although for some reason the count is 0 regardless of how many tables are in the file. 我正在尝试将一个单词文件中的所有表读入一个列表,尽管由于某种原因,无论文件中有多少个表,计数均为0。 Here's my code. 这是我的代码。

public void FindAndReplace(string DocPath)
{
  using (WordprocessingDocument doc = WordprocessingDocument.Open(DocPath, true))
  {
    using (StreamReader reader = new StreamReader(doc.MainDocumentPart.GetStream()))
    {
      //Text titlePlaceholder = doc.MainDocumentPart.Document.Body.Descendants<Text>().Where((x) => x.Text == "Compliance Review By:").First();
      List<Table> tables = doc.MainDocumentPart.Document.Descendants<Table>().ToList();
      System.Console.WriteLine(tables.Count);

tables.Count = 0. What am I doing wrong? table.Count =0。我在做什么错?

If all you're trying to do is READ the tables, then there's no need to open the document for editing (which is what you're doing currently) 如果您要做的只是读取表,那么就无需打开文档进行编辑(这是您当前正在做的事情)

Set the second parameter to false in WordprocessingDocument.Open() to open for reading. 在WordprocessingDocument.Open()中将第二个参数设置为false以打开以进行读取。 This will prevent the error related to opening an entry more than once in Update mode (I assume that's what you're running into anyway). 这样可以避免与在更新模式下多次打开一个条目有关的错误(无论如何我都认为这是您遇到的问题)。

Solution based on chatter 基于聊天的解决方案

The real culprit here has to do with using the wrong OpenXml namespace when examining tables in the document. 真正的罪魁祸首是在检查文档中的表时使用了错误的OpenXml命名空间。 When looking for Descendants of type Table, the passed-in type must be OpenXml. 查找Table类型的后代时,传入的类型必须为OpenXml。 Wordprocessing .Table, NOT OpenXml. 文字处理表不是 OpenXml。 Drawing .Table 绘图表

I don't know what type of object the OpenXml.Drawing.Table is used for. 我不知道OpenXml.Drawing.Table用于什么类型的对象。 I'll ask about this in a separate question. 我将在另一个问题中对此进行询问。

You probably are referencing a wrong Table . 您可能引用了错误的Table This should work: 这应该工作:

var tables = doc.MainDocumentPart.Document.Descendants<DocumentFormat.OpenXml.Wordprocessing.Table>().ToList();

Anu start had the answer in the comments. 阿努开始有评论中的答案。 The problem was that I was using an incorrect namespace. 问题是我使用了不正确的名称空间。 Instead of using DocumentFormat.OpenXml.Wordprocessing.Table I was using DocumentFormat.OpenXml.Drawing.Table 我不是使用DocumentFormat.OpenXml.Wordprocessing.Table,而是使用DocumentFormat.OpenXml.Drawing.Table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM