Adding Worksheets to a Workbook |
The Worksheets collection holds the worksheets of a workbook. A new workbook has one worksheet. Add more worksheets with AddWorksheet, with a default name or with the name you give.
Add a worksheet and get the worksheets by their zero based index or by name:
// the first worksheet of a new workbook ExcelWorksheet firstWorksheet = workbook.Worksheets[0]; firstWorksheet.Name = "Summary"; // a new worksheet, added after the existing ones ExcelWorksheet chartWorksheet = workbook.Worksheets.AddWorksheet("Simple Chart"); // the same worksheet by index and by name ExcelWorksheet byIndex = workbook.Worksheets[1]; ExcelWorksheet byName = workbook.Worksheets["Simple Chart"]; // all the worksheets foreach (ExcelWorksheet sheet in workbook.Worksheets) Console.WriteLine(sheet.Name);
Rows and columns can be inserted and deleted; the cells, merged ranges and pictures below or to the right move. The row and column indexes are one based:
// insert an empty row before row 1 and an empty column before column 3 worksheet.InsertRow(1); worksheet.InsertColumn(3); // set the width of column 1 and the height of row 1 worksheet.SetColumnWidthInChars(1, 30); worksheet.SetRowHeightInPoints(1, 24); // hide the grid lines in Excel worksheet.ShowGridLines = false;
A worksheet that contains only a chart is a chart worksheet; see Adding Chart Shapes and Chart Worksheets.