1

How can I find some value from cell and replace by new value in Excel?

I tryed this but it doesn't works:

Microsoft.Office.Interop.Excel.Application xlapp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb =default(Microsoft.Office.Interop.Excel.Workbook);

wb = xlapp.Workbooks.Open(FileName.ToString());

wb.Worksheets[0].Cells.Replace("find","replace");
3
  • What do you mean it doesn't works? Any exception or..? Commented Mar 21, 2013 at 10:03
  • If that's all your code does, then it should work fine, but you're going to have to be more specific about where it doesn't work and how you know. Commented Mar 23, 2013 at 0:04
  • 1
    For anyone who finds this later. Worksheets[x] is not 0-based it starts at 1. wb.Sheets.Count; can get you the number of sheets and a for loop can iterate the find-replace through every one of them. Also, you need wb.Save(); and wb.Close(); at the end to actually save the changes and close the document. Commented May 22, 2019 at 20:00

3 Answers 3

2

I would recommend you use NPOI which can be accessed either via codeplex or directly through Nuget in Visual Studio. It gives you the ability to easily upload, edit and create spreadsheets in .NET

Example of uploading a spreadsheet:

HSSFWorkbook hssfworkbook;

void InitializeWorkbook(string path)
{
    //read the template via FileStream, it is suggested to use FileAccess.Read to prevent file lock.
    //book1.xls is an Excel-2007-generated file, so some new unknown BIFF records are added. 
    using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
    {
        hssfworkbook = new HSSFWorkbook(file);
    }
}

You can then use the IRow and ICell collections of the spreadsheet to locate and edit the data you need before doing an export.

More examples can be found here

Sign up to request clarification or add additional context in comments.

Comments

2

All you have to do is replace

wb.Worksheets[0].Cells.Replace("find","replace");

with

wb.Worksheets[1].Cells.Replace("find","replace");

Comments

2

If interested, you can use GemBox.Spreadsheet for this, like so:

SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");

// Load your XLS, XLSX, ODS or CSV file.
ExcelFile wb = ExcelFile.Load(FileName.ToString());
ExcelWorksheet ws = wb.Worksheets[0];

// Replace all "find" occurances with "replace" text.
int row, column;
while(ws.Cells.FindText("find", out row, out column))
    ws.Cells[row, column].ReplaceText("find", "replace");

// Save your XLS, XLSX, ODS or CSV file.
wb.Save(FileName.ToString());

Also you can find another searching in Excel example here.

Comments

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.