C#如何使用Interop重命名Excel工作表

时间:2013-05-28 16:09:51

标签: c# excel

我需要创建Excel电子表格,然后我需要重命名工作表。我做错了什么?

这是我到目前为止的代码:

using System;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;

public class CreateExcelWorksheet
{
    static void Main()
    {
        Excel.Application oXL;
        Excel._Workbook oWB;
        Excel._Worksheet oSheet;

        oXL = new Excel.Application();
        oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
        oSheet = (Excel._Worksheet)oWB.ActiveSheet;

        oSheet.Cells[1, 1] = "First Name";
        oSheet.Cells[1, 2] = "Last Name";
        oSheet.Cells[1, 3] = "Full Name";
        oSheet.Cells[1, 4] = "Salary";

        //Format A1:D1 as bold, vertical alignment = center.
        oSheet.get_Range("A1", "D1").Font.Bold = true;
        oSheet.get_Range("A1", "D1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
        oSheet.Name = "NewOne";

        string filename = "C:\\" + DateTime.Now.ToString("dd_MM_yy_hhmmss");
        oWB.SaveAs(filename + "asdaa" + ".xlsx");

        oWB.Close();
    }
}

2 个答案:

答案 0 :(得分:8)

oWB.Worksheets是您找到工作表的地方。

可以通过索引Worksheets[1](或2或3 ...)

来获取它们

可以按名称Worksheets["SheetName"]

取名

它们是对象,所以将它们转换为(Worksheet)

Worksheet oSheet = (Worksheet)oWB.Worksheets["TheSheetYouWant"];

更改名称:oSheet.Name = "NewName";

答案 1 :(得分:6)

更短: workbook.Worksheets[1].Name = "Sheet Name";