Question

I need to create a new Excel Workbook with 4 Worksheets and custom name each worksheet. I tried this but it gives me a COMEXception after adding the 1st sheet

docExcel = new Microsoft.Office.Interop.Excel.Application();
docExcel.Visible = true;
docExcel.DisplayAlerts = false;
_Workbook workbooksExel = docExcel.ActiveWorkbook;
workbooksExcel = (_Workbook)(docExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet));
Worksheet worksheet = (Worksheet)docExcel.Worksheets["Sheet 1"];
worksheet.Name = "WS 1";
Worksheet worksheet1 = (Worksheet)docExcel.Worksheets["Sheet 2"];
workhseet1.Name = "WS 2";
Worksheet worksheet2 = (Worksheet)docExcel.Worksheets["Sheet 3"];
worksheet2.Name = "WS 3";
Worksheet worksheet3 = (Worksheet)docExcel.Worksheets["Sheet 4"];
worksheet3.Name = "WS 4";
Was it helpful?

Solution

Try this -- it is what I use to do the same thing

Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = ap.WOrkbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
Sheets xlSheets = null
Worksheet xlNewSheet = null;
xlSheets = workbook.Sheets as Sheets;
app.Visible = true;
//And you can do this as many times as the sheets you want to add
worksheet = workbook.Worksheets[1];
worksheet.Name = "Sheet 1";
worksheet = workbook.Worksheets[2];
worksheet.Name = "Sheet 2";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top