简体   繁体   中英

How to rename excel sheet name dynamically in C#

我创建了一个excel工作簿,其中包含许多工作表,如sheet1,sheet2,...等。如何在C#中动态重命名这些选项卡名称?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM