Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# how to rename Excel Sheet using Interop

Tags:

c#

excel

I need to create an Excel spreadsheet and then I need to rename the sheets. What am I doing wrong?

Here is the code I have so far:

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();
    }
}
like image 408
Bhaskar Mishra Avatar asked May 28 '13 16:05

Bhaskar Mishra


2 Answers

oWB.Worksheets is where you find the sheets.

Can take them by index Worksheets[1] (or 2, or 3...)

Can take them by name Worksheets["SheetName"]

They come as object, so cast them to (Worksheet).

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

To change name: oSheet.Name = "NewName";

like image 52
Daniel Möller Avatar answered Sep 28 '22 18:09

Daniel Möller


Even shorter: workbook.Worksheets[1].Name = "Sheet Name";

like image 22
OzW Avatar answered Sep 28 '22 17:09

OzW