如何访问表格中与 MS Word 具有不同单元格宽度的列 [英] How to access columns in a table that have different cell widths from MS Word

查看:13
本文介绍了如何访问表格中与 MS Word 具有不同单元格宽度的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从表格的第一列中获取单元格.在Foreach(Cells c in rng.Tables[1].Columns[1].Cells)"中出现异常,因为表格包含具有混合单元格宽度的列.

I am trying to get the cells from 1st column in a table. Getting exception in the "Foreach(Cells c in rng.Tables[1].Columns[1].Cells)" because the table contains columns that have mixed cell widths.

例如:第一行有4个单元格,第二行只有2个单元格(2个单元格合并在一起)

for eg: in first row, there are 4 cells and in second row, there are only 2 cells (2 cells merged together)

错误消息:无法访问此集合中的各个列,因为表格具有混合单元格宽度."

Document oDoc = open word document  
foreach (Paragraph p in oDoc.Paragraphs)  
    {  
    Range rng = p.Range;  
  /* 

  */  
  foreach (Cell c in rng.Tables[1].Columns[1].Cells)  
  {  
     //....  
  }  
 }  

推荐答案

代替在第二个循环中使用 foreach 循环,您是否可以使用像这样的 for 循环来遍历所有单元格:

Instead of using a foreach loop in your second loop, can you instead use a for loop like so to iterate over all cells:

        for (int r = 1; r <= rng.Tables[1].Row.Count; r++)
        {
            for (int c = 1; c <= rng.Tables[1].Columns.Count; c++)
            {
                try
                {
                    Cell cell = table.Cell(r, c);
                    //Do what you want here with the cell
                }
                catch (Exception e)
                {
                    if (e.Message.Contains("The requested member of the collection does not exist."))
                    {
                       //Most likely a part of a merged cell, so skip over.
                    }
                    else throw;
                }
            }
        }

这篇关于如何访问表格中与 MS Word 具有不同单元格宽度的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆