1

I would like to export some data to Excel with a custom name sheet.

How can I change the sheet name from C#?

Here is my code:

var workbook = new HSSFWorkbook();
var font = workbook.CreateFont();
font.Boldweight = HSSFFont.BOLDWEIGHT_BOLD;
sheet.SetColumnWidth(0, 10 * 256);
sheet.SetColumnWidth(1, 30 * 256);
headerRow.CreateCell(0).SetCellValue("Column1");
headerRow.CreateCell(1).SetCellValue("Column2");

int rowNumber = 1;

//Populate the sheet with values from the grid data
foreach (var m in model)
{
    //Create a new row
    var row = sheet.CreateRow(rowNumber++);
    //Set values for the cells
    row.CreateCell(0).SetCellValue(m.Column1);
    row.CreateCell(1).SetCellValue(m.Column2);
}

1 Answer 1

3
Workbook workbook = new HSSFWorkbook();
Worksheet sheet = (Worksheet)workbook.Worksheets[index];
// you can also use the current worksheet name here

To change the name, you have to write

sheet.Name = "TheNewWorksheetName";
2
  • The namespace Worksheet doesn't exists. I found the way to modify the name. var sheet = workbook.CreateSheet(NameofSheet);
    – Ark
    Apr 30, 2014 at 14:10
  • Great, but workbook.CreateSheet(NameOfSheet) will create a new worksheet (and add it to the worksheets in the excel workbook) and not rename an existing one. Apr 30, 2014 at 21:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.