Find and Replace all string using EPPLUS

痞子三分冷 提交于 2020-01-24 00:59:30

问题


How to find and replace all the string in worksheet using EPPLUS?

on Excel Macro it is simply as like this:

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

回答1:


The fast way to search and replace cell values in EPPLus is to use Linq in EEPlus. I wrote a simple example for you. My spread-sheet got almost 10 columns and 1157 rows and it took less than a second to search and replace values.

    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();
    }



回答2:


I used your example to come up with a function. I am calling this function again and again to find a few Unique reference strings in my excel template and replace them with values retrieved from a table. However I noticed that the function errors out every time saying "Object reference not set to an instance of object". Here is my function: Not sure what's wrong. Please can you advise.

    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


来源:https://stackoverflow.com/questions/56312166/find-and-replace-all-string-using-epplus

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!