使用 EPPLUS 查找并替换所有字符串

Find and Replace all string using EPPLUS

如何使用EPPLUS查找和替换工作表中的所有字符串?

在Excel宏上就是这样:

Cells.Replace What:="k", Replacement:="w", LookAt:=xlPart, SearchOrder _
    :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

EPPLus 中搜索和替换单元格值的快速方法是在 EEPlus 中使用 Linq。我为你写了一个简单的例子。我的 spread-sheet 得到了将近 10 列和 1157 行,搜索和替换值用了不到一秒钟的时间。

    var valueToSearch = "Foo";
    var valueToReplace = "Bar";
    var sheetName = "Sheet1";
    var filePath = @"d:\foo-bar.xlsx";

    using (var excel = new ExcelPackage(new System.IO.FileInfo(filePath)))
    {
        var ws = excel.Workbook.Worksheets[sheetName];

        // search in all cells
        // https://github.com/JanKallman/EPPlus/wiki/Addressing-a-worksheet
        var query = from cell in ws.Cells["A:XFD"] 
                    where cell.Value?.ToString().Contains(valueToSearch) == true
                    select cell;

        foreach(var cell in query)
        {
            cell.Value = cell.Value.ToString().Replace(valueToSearch, valueToReplace);
        }

        excel.Save();
    }

我用你的例子想出了一个函数。我一次又一次地调用此函数以在我的 excel 模板中找到一些唯一引用字符串,并将它们替换为从 table 中检索到的值。但是我注意到每次说 "Object reference not set to an instance of object" 时函数都会出错。这是我的功能:不确定出了什么问题。请你指教。

    Private Function FindAndReplaceTextInExcel_EPPlus(oWS As ExcelWorksheet, strStringToFind As String, strStringToAdd As Object) As Boolean
        Try
            '
            Dim oExcelRangeBase = From cell In oWS.Cells("A:XFD") Where cell.Value.ToString().ToUpperInvariant.Equals(strStringToFind.ToUpperInvariant) = True Select cell

            If Not IsNothing(oExcelRangeBase) Then
                For Each cell In oExcelRangeBase
' I tried both options below but in the loop the function gives error.
                    cell.Value = strStringToAdd.ToString  'cell.Value.ToString.Replace(strStringToFind, strStringToAdd)
                    ' MsgBox(cell.Address.ToString)
                    FindAndReplaceTextInExcel_EPPlus = True
                    Exit For
                Next

            End If

        Catch ex As Exception
            '  MsgBox(GetLineNumber(ex) & vbCrLf & ex.Message)

        End Try
        Return FindAndReplaceTextInExcel_EPPlus
    End Function