How to create a new worksheet in Excel file c#?

Bryuk picture Bryuk · May 23, 2013 · Viewed 51.6k times · Source

I need to create a very big Excel file, but excel file in one worksheet can contain up to 65k rows. So, i want to divide all my info into several worksheets dynamical. This is my approximate code

 //------------------Create Excel App--------------------
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(numberOfLetters);

     foreach (string letter in letters)
     {
      xlWorkSheet.Cells[rowIndex, 1] = letter; 
      rowIndex++;
     }

xlWorkBook.SaveAs(pathXL, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

How I can add new worksheet inside of my foreach loop and using some condition give a name to worksheet (which user can see in Excel at the bottom of the page in list)?

Some like that

    foreach (string letter in letters)
    {
      if (letter == SOME)
      {
        AddNewWorksheet and give name SOME
      }
        xlWorkSheet.Cells[rowIndex, 1] = letter; 
        rowIndex++;
    }

And how to save all worksheets at the end?

Answer

Andrey Gordeev picture Andrey Gordeev · May 23, 2013

To add a new worksheet to the workbook use this code:

var xlSheets = xlWorkBook.Sheets as Excel.Sheets;
var xlNewSheet = (Excel.Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
xlNewSheet.Name = "newsheet";

// Uncomment a line below if you want the inserted sheet to be the last one
//xlWorkBook.Sheets.Move(After: xlWorkBook.Sheets.Count);

To save the workbook call Save() method:

xlWorkBook.Save();