首页 文章

在C#中重命名Excel工作表名称

提问于
浏览
1

VS 2008 / C# .

在传递电子表格的文件路径时,我需要重命名工作表 .

如何将Excel工作表的Sheet1重命名为“ABC” .

我们将Excel工作表导出到SQL数据库 . Excel工作表中的记录由最终用户手动编辑和更新 . 列值可以具有不同的数据类型 .

默认情况下,电子表格将有三张表格作为Sheet1,Sheet2,Sheet3 .

最终用户,通常在Sheet1上工作 . 我们需要为这个Sheet1维护一个静态名称,这有助于我们将Sheet1导出到SQL数据库 .

如果我们将Sheet1重命名为ABC,我们将保持相同的名称 . 我们不能像那样导出默认表 . 因为,最终用户可能会更改其名称或坚持使用默认名称 .

为了避免混淆,我们决定重命名Spread Sheet的Sheet1 .

1 回答

  • 6

    C#3.0

    using Microsoft.Office.Interop.Excel;
    

    然后

    object oMissing = System.Reflection.Missing.Value;
    
    Microsoft.Office.Interop.Excel.ApplicationClass xl = new Microsoft.Office.Interop.Excel.ApplicationClass();
    
    Microsoft.Office.Interop.Excel.Workbook xlBook;
    Microsoft.Office.Interop.Excel.Worksheet xlSheet;
    
    string laPath = System.IO.Path.GetFullPath("C:\\ExcelSheet.xls");
    xlBook = (Workbook)xl.Workbooks.Open(laPath, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
    
    xlSheet = (Worksheet)xlBook.Worksheets.get_Item(1);
    xlSheet.Name = "CIAO";
    xlBook.Save();
    xl.Application.Workbooks.Close();
    

    C#4.0

    区别在于:不再使用 System.Reflection.Missing.Value 并使用DLR(动态语言运行时)

    using System.IO;
    
    using Excel = Microsoft.Office.Interop.Excel;
    using Word = Microsoft.Office.Interop.Word;
    

    然后

    var excelFile = Path.GetFullPath("C:\\ExcelSheet.xls");
    var excel = new Excel.Application();
    var workbook = excel.Workbooks.Open(excelFile);
    var sheet = (Excel.Worksheet)workbook.Worksheets.Item[1]; // 1 is the first item, this is NOT a zero-based collection
    sheet.Name = DateTime.Now.ToString("yyyyMMddHHmmss");
    workbook.Save();
    excel.Application.Workbooks.Close();
    

相关问题