TuckRollworthy
TuckRollworthy

Reputation: 105

Having an issue renaming Excel worksheet

I have write a console C# program to generate a Spreadsheet. However when I try to name the second sheet, that name over writes the first sheet.

///// create sheet1
Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet WorkSheet = (Worksheet)wb.Worksheets[1];
WorkSheet.Name = "Work Sheet";

///// create sheet2

wb.Sheets.Add();
Microsoft.Office.Interop.Excel.Worksheet staffCosts = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[2];
staffCosts.Name = "Staff Costs";

Something I have missed and no doubt it will be simple.

Upvotes: 2

Views: 77

Answers (1)

GSerg
GSerg

Reputation: 78134

By default the new worksheet becomes the first sheet. All other sheets are shifted to the right, so Worksheets[2] refers to what used to be Worksheets[1].

In any case this is how you should have written it:

staffCosts = wb.Sheets.Add();
staffCosts.Name = "Staff Costs";

Upvotes: 3

Related Questions