I need help in writing a C# code which basically should take excel file as input and check if the excel file contains a specific worksheet or tab and if yes rename that tab with another name. The program should support .net 3.5 and excel 2007. Please provide me some examples. Thanks in advance.
Asked
Active
Viewed 1.5k times
3 Answers
5
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
string lookFor="TabName1";
foreach (Microsoft.Off.Interop.Excel.Worksheet w in wb.Worksheets)
{
if (w.Name == lookFor)
//match exists rename
w.Name = lookFor + "_renamed";
}

JonH
- 32,732
- 12
- 87
- 145
-
As per ZombieSheep's comment above, you need to verify that the new name doesn't already exist in the workbook. – Peter M Apr 04 '11 at 13:26
-
@ Peter and ZombieSheep....Yes you are 100% correct i will try to loop through the above code and try to give guide lines to the users explaining them the situation..... – S.. Apr 04 '11 at 13:47
-
John....The code is working fine, but when i open the file, its saying the file is locked for editing by "S.."(which is my name in my system). I understand the program internally opens the file to rename but how do we close that. – S.. Apr 04 '11 at 16:44
-
@S.. - When you open the file make sure when you are done with it to close the workbook `wb.Close` and `excel.Quit` `excel=null` – JonH Apr 04 '11 at 17:00
-
@John..This below code solved the problem GC.Collect(); GC.WaitForPendingFinalizers(); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(WB); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_Excel); – S.. Apr 04 '11 at 17:20
-
Ahh yes there was a stack overflow thread about that one time. You might want to post the link to that. – JonH Apr 04 '11 at 17:22