2

I would like to find and replace a group of text in Excel using C#, moreover I want this replace to happen to text in the first row only.

I have used Google and found a few paid resource like Aspose API,Spire.Xls,etc, but I am looking for an open source resource or any other efficient way to achieve this. Please suggest.

1
  • Exactly, there is two main solution OpenXml (does not require Excel software to be installed) and the interop solution it use an instance of Excel to handle your file (so it require Excel to be installed) So What did you try ? Commented Nov 8, 2016 at 10:45

2 Answers 2

6

Try this:

Public static void ReplaceTextInExcelFile(string filename, string replace, string replacement)
{
    object m = Type.Missing;

    // open excel.
    Application app = new ApplicationClass();

    // open the workbook. 
    Workbook wb = app.Workbooks.Open(
        filename,
        m, false, m, m, m, m, m, m, m, m, m, m, m, m);

    // get the active worksheet. (Replace this if you need to.) 
    Worksheet ws = (Worksheet)wb.ActiveSheet;

    // get the used range. 
    Range r = (Range)ws.UsedRange;

    // call the replace method to replace instances. 
    bool success = (bool)r.Replace(
        replace,
        replacement,
        XlLookAt.xlWhole,
        XlSearchOrder.xlByRows,
        true, m, m, m);

    // save and close. 
    wb.Save();
    app.Quit();
    app = null;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Here is a code that worked for me

Excel.Range range = exWS.UsedRange;
range.Replace2("look_for", "replace", Excel.XlLookAt.xlWhole);

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.