Search code examples
c#excelexcel-interop

How can I rename Excel worksheets using NetOffice?


I am trying to use NetOffice to create excel workbooks in my c# application and have caught a snag trying to rename worksheets and using sorts on ranges of cells. The following lines of code are not recognized by NetOffice and I am struggling to find a way to rename worksheets and sort ranges of cells using NetOffice.

workbook.Worksheets[sheetCountPlusONe].name = "Event " + sheetCountPlusONe.ToString() + " Results";

And this also doesn't work. This is where I am declaring and sorting a range of cells:

Excel.Range valueRange;
Excel.Range placeRange;
placeRange = worksheet.get_Range("A14", "A" + (14 + (registrationForm.numberofCompetitors - 1)).ToString());
valueRange = worksheet.get_Range("A14", "K"+(14+(registrationForm.numberofCompetitors-1)).ToString());
valueRange.Sort(valueRange.Columns[3, Type.Missing], Excel.XlSortOrder.xlDescending, Type.Missing, Type.Missing, Excel.XlSortOrder.xlAscending, Type.Missing, Excel.XlSortOrder.xlAscending, Excel.XlYesNoGuess.xlGuess, Type.Missing, Type.Missing, Excel.XlSortOrientation.xlSortColumns, Excel.XlSortMethod.xlPinYin, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal);
placeRange.Sort(placeRange.Columns[1, Type.Missing], Excel.XlSortOrder.xlAscending, Type.Missing, Type.Missing, Excel.XlSortOrder.xlAscending, Type.Missing, Excel.XlSortOrder.xlAscending, Excel.XlYesNoGuess.xlGuess, Type.Missing, Type.Missing, Excel.XlSortOrientation.xlSortColumns, Excel.XlSortMethod.xlPinYin, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal, Excel.XlSortDataOption.xlSortNormal); 

Solution

  • I am wondering about your question. The following code works fine:

    Excel.Application excelApplication = new Excel.Application();
    Excel.Workbook workBook = excelApplication.Workbooks.Add();
    Excel.Worksheet workSheet = workBook.Worksheets[1] as Excel.Worksheet;
    workSheet.Name = "AnyNameYouWant";