0

我正在使用 for 循环获取单词表的单元格的索引,这对于更大的表来说需要很多时间,有没有办法在没有 for 循环的情况下做到这一点?

public static int[] GetColumnIndex(Xceed.Words.NET.Table table, string columnName, int endRow,int k)
        {
            int[] data = { -1, -1 };
            for (int j = k; j < endRow; j++)
            {
                for (int i = 0; i < table.Rows[j].Cells.Count; ++i)
                {
                    if (table.Rows[j].Cells[i].Paragraphs[0].Text.Equals("«" + columnName + "»"))
                    {
                        data[0] = j;
                        data[1] = i;
                        return data;
                    }
                }
            }

            return data;
        }

我从另一个函数中调用这个函数

int startRow = 0, endRow = 0;
int[] ind;
DocX doc;
doc = DocX.Load(fileName);
Xceed.Words.NET.Table t;
t = doc.Tables[0];
endRow = t.Rows.Count;
System.Data.DataTable dt = new DataTable();
dt = reader(report.Query);
foreach (DataColumn col in dt.Columns)
{
    ind = GetColumnIndex(t, col.ColumnName, endRow,2);

    //...more code here...
}

4

1 回答 1

1

您可以做一些事情来优化您的算法(基于您的访问模式)是您搜索同一个表的次数(事实上,由于您正在搜索表中的列名,搜索次数会随着表的获取而迅速增加大的)。因此,值得将表中的数据转换为由单词索引的数据结构(例如,排序字典)。

首先,创建一个包含表格内容的类。这样当你想搜索同一张表时,你可以使用同一个类的实例,避免重新创建基于排序字典的数据结构:

public class XceedTableAdapter
{
   private readonly SortedDictionary<string, (int row, int column)> dict;

   public XceedTableAdapter(Xceed.Words.NET.Table table)
   {
      this.dict = new SortedDictionary<string, (int, int)>();
      // Copy the content of the table into the dict.
      // If you have duplicate words you need a SortedDictionary<string, List<(int, int)>> type. This is not clear in your question.
      for (var i = 0, i < rowCount; i++)
      {
          for (var j = 0; j < columnCount; j++)
          {
              // this will overwrite the index if the text was previously found: 
              this.dict[table.Rows[i].Cells[j].Paragraphs[0].Text] = (i, j);
          }
      }
   }

   public (int, int) GetColumnIndex(string searchText)
   {
      if(this.dict.TryGetValue(searchText, out var index))
      {
          return index;
      }

      return (-1, -1);
   }
}

现在你只循环整个表一次,随后的搜索将在 O(log n) 中发生。如果 Xceed 具有将数据表转换为字典的功能,那将非常方便。我不熟悉这个库。

现在你可以像这样搜索它:

var searchableTable = new XceedTableAdapter(doc.Tables[0]);

foreach (var col in dt.Columns)
{
   ind = searchableTable.GetColumnIndex(col);
}
于 2019-08-21T06:27:46.700 回答