2017-05-05 97 views
0

我想用gembox更新excel文件。我想让gembox在excel文件中搜索某个字符串,并更新所有匹配项。但方法FindText()只返回第一次出现。Gembox查找和更新单元格

我尝试了以下操作,但会导致无限循环,出于某种原因,行和列不会更新到下一个搜索结果。

private void RenameSubCategory(ExcelWorksheet sheet, string subCategoryOld, string subCategoryNew) 
    { 
    int row, column; 
    while (sheet.Cells.FindText(subCategoryOld, false, false, out row, out column)) { 
     sheet.Cells[row, column].Value = subCategoryNew; 
    } 
    } 

回答

1

有没有可能是你的subCategoryNew文本包含subCategoryOld文本?
换句话说,你也许有类似以下内容:

RenameSubCategory(sheet, "Sample", "Sample New"); 

这将导致无限循环,因为你一定会找到在被设置为"Sample New"文本的单元格"Sample"
而不是尝试使用的ReplaceText方法之一,如下所示:

sheet.Cells.ReplaceText("Sample", "Sample New"); 

,或者尝试使用以下:

private static void RenameSubCategory(ExcelWorksheet sheet, string subCategoryOld, string subCategoryNew) 
{ 
    foreach (ExcelRow row in sheet.Rows) 
     foreach (ExcelCell cell in row.AllocatedCells) 
      if (cell.ValueType == CellValueType.String && 
       cell.StringValue.Contains(subCategoryOld)) 
       cell.Value = subCategoryNew; 
} 

我希望这有助于。