How to rename excel sheet name dynamically in C#

早过忘川 提交于 2019-11-28 03:13:54

问题


I have created an excel workbook with many sheets like sheet1, sheet2,... etc. How can I rename these tab names dynamically in C#?


回答1:


You didn't spedify how do you access the excel file. However, example from here might be useful for you if you're using Microsoft.Office.Interop.Excel. Note that it opens first sheet in the file, line: (Worksheet)xlBook.Worksheets.get_Item(1)

using Excel = Microsoft.Office.Interop.Excel; 

    object oMissing = System.Reflection.Missing.Value;
    Excel.ApplicationClass xl=new Excel.ApplicationClass();
        Excel.Workbook xlBook;
        Excel.Worksheet xlSheet;
        string laPath = Server.MapPath(@"\excel\xl_table.xls");
        xlBook = (Workbook)xl.Workbooks.Open(laPath,oMissing,
          oMissing,oMissing,oMissing ,oMissing,oMissing,oMissing
         ,oMissing,oMissing,oMissing,oMissing,oMissi ng,oMissing,oMissing);
        xlSheet = (Worksheet)xlBook.Worksheets.get_Item(1);
        xlSheet.Name = "CIAO";
        xlBook.Save();
        xl.Application.Workbooks.Close();



回答2:


One short note: If you don't need to specify them, you can get rid of all these optional parameters and use the short form:

xlBook = (Workbook)xl.Workbooks.Open(laPath);

Regards, Jörg



来源:https://stackoverflow.com/questions/4561012/how-to-rename-excel-sheet-name-dynamically-in-c-sharp

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