Ark
Ark

Reputation: 101

How to change the Worksheet name in Excel?

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);
}

Upvotes: 1

Views: 3030

Answers (1)

Manish Dalal
Manish Dalal

Reputation: 1796

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";

Upvotes: 3

Related Questions