Administrator

Administrator

  • Tech Writer
  • 2.2k
  • 1.5m

Adding new worksheet to existing Excel workbook

Apr 11 2003 11:11 AM
Hi, I am trying to create an Excel workbook with multiple worksheets. It seems that a workbook is created with only 1 worksheet by default. I have no problems accessing the first sheet and writing data to it, but I can't get the Add method of Excel.Sheets to work. I may be using the wrong arguments. The error I get is as follows: An unhandled exception of type "System.Runtime.InteropServices.COMException" occured in Cat.exe Additional information: Exception from HRESULT: 0x800A03EC I found a number of examples in VB, but the Add method in VB does not require any arguments. Does anyone know how this method in C#? Many thanks in advance! Helene Source code: private Excel.Application excel; private Excel.Workbook workbook; private Excel.Sheets sheets; excel = new Excel.Application(); workbook = excel.Application.Workbooks.Add(true); sheets = (Excel.Sheets) workbook.Worksheets; int sheetIndex = 0; object type = Excel.XlSheetType.xlWorksheet; foreach (string region in regionsList){ sheetIndex++; Excel.Worksheet worksheet; if (sheetIndex == 1){ worksheet = (Excel.Worksheet) sheets.get_Item(sheetIndex); } else { worksheet = (Excel.Worksheet) sheets.Add(sheets.get_Item(sheetIndex-1), null, 1 , type); } worksheet.Name = regionName; }

Answers (2)