Search code examples
c#epplusepplus-4

Generate unique name for multiple worksheets in a for loop


I am using for loop to generate some worksheets, and I want to give each one a unique name. All I get is Sheet1, Sheet2, Sheet3, and so on.

Below is my code:

var package = new ExcelPackage();

for (var i = 0; i < ds.Tables.Count; i++)
{
    var ws = package.Workbook.Worksheets.Add(String.Format("Sheet{0}", i));

    ws.Cells["A1"].LoadFromDataTable(i == 0 
        ? Transpose(ds.Tables[i].Copy()).DefaultView.ToTable() 
        : ds.Tables[i], true, TableStyles.Medium1);

    ws.Cells[ws.Dimension.Address].AutoFitColumns();
    ws.Cells["A:J"].Style.Numberformat.Format = "#,##0";                          
} 

Solution

  • You haven't shown where the names are coming from, but probably the best way would be to use the name from some field in the same data source that you're using to populate the sheet.

    Here's one one way to give them each unique names would be to have them stored in a list, which you can access using the same index that you're using currently. Of course you have to somehow ensure that the names are in the correct order in your list:

    var sheetNames = new List<string> { "Summary", "EmployeeData", "Benefits" };
    
    for (var i = 0; i < ds.Tables.Count; i++)
    {
        // Choose a name from the list or use 'Sheet1, 2, 3' if we don't have enough names
        var sheetName = i < sheetNames.Count 
            ? sheetNames[i] 
            : String.Format("Sheet{0}", sheetNames.Count - i);
    
        var ws = package.Workbook.Worksheets.Add(sheetName);