Search code examples
c#epplus

Find and Replace all string using EPPLUS


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

Solution

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