简体   繁体   English

如何使用C#在特定标题旁边的Word文档中获取MS Word表?

[英]How to get MS Word table in a word document next to specific heading using C#?

I am trying to identify specific value under corresponding column in a word table using c#. 我正在尝试使用c#在单词表的相应列下标识特定值。 Tried: 1- If table index is known - get table range as text and iterate over it to reach certain row and column. 尝试:1-如果表索引已知-将表范围获取为文本并对其进行迭代以到达特定的行和列。

Problem is- Table comes under certain heading anywhere in the document. 问题是-表位于文档中任何位置的特定标题下。 Index is variable, so can't rely on index. 索引是可变的,因此不能依赖索引。

As Cindy has pointed out, the question in a current form is too broad. 正如辛迪指出的那样,当前形式的问题过于广泛。 I'm not sure how you're reading your documents. 我不确定您如何阅读文件。 Also, I'm not sure what you mean by "certain heading", do you know what text will be before the targeted table? 另外,我不确定您所说的“某些标题”是什么意思,您知道目标表之前的文字是什么吗?

Nevertheless, you could check out the following sample, the code uses GemBox.Document : 不过,您可以查看以下示例,该代码使用GemBox.Document

string cellValue = null;

string headingText = "My Heading Text";
int rowIndex = 0;
int columnIndex = 0;

// Load Word document.
DocumentModel document = DocumentModel.Load("Sample.docx");

// Iterate through all paragraphs.
foreach (Paragraph paragraph in document.GetChildElements(true, ElementType.Paragraph))
{
    // Check that paragraph is of heading style.
    ParagraphStyle style = paragraph.ParagraphFormat.Style;
    if (style == null || !style.Name.Contains("heading"))
        continue;

    // Check that heading paragraph contains our text.
    if (!paragraph.Content.ToString().Contains(headingText))
        continue;

    // Get first table after the heading paragraph.
    Table table = new ContentRange(paragraph.Content.End, document.Content.End)
        .GetChildElements(ElementType.Table)
        .Cast<Table>()
        .First();

    // Get cell value.
    cellValue = table.Rows[rowIndex].Cells[columnIndex].Content.ToString();
    break;
}

Console.WriteLine(cellValue);

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

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