Excel Automation - creating a new worksheet

Posted by Andrew Shepherd on Stack Overflow See other posts from Stack Overflow or by Andrew Shepherd
Published on 2010-06-07T22:58:29Z Indexed on 2010/06/07 23:02 UTC
Read the original article Hit count: 317

Filed under:
|
|

I am attempting what seems like a simple task: using C# to create a new Excel document containing new worksheets.

For some reason, I am getting a strange COM error (0x800A03EC)

Has anyone managed to get this to work? Does anyone have suggestions as to how to troubleshoot this?

I've isolated this into the minimum amount of code:

using Microsoft.Office.Interop.Excel;
using System.Diagnostics;

namespace ExcelAutomation
{
    public static class ExcelTests
    {
        public static void CreateWorksheet()
        {
            try
            {
                var app = new Microsoft.Office.Interop.Excel.Application();
                app.Visible = true;
                var workBooks = app.Workbooks;
                var newWorkbook = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
                Worksheet existingWorksheet = (Worksheet)newWorkbook.Sheets[1];

                Worksheet workSheet = (Worksheet)newWorkbook.Sheets.Add
                        (
                            null, // before
                            existingWorksheet,
                            null, // 1,
                            null //XlSheetType.xlWorksheet
                        );
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                Trace.WriteLine(string.Format("Caught COMException. Message: \"{0}\"", ex.Message));  
            }
        }
    }
}

The output window now says:

Caught COMException. Message: "Exception from HRESULT: 0x800A03EC"

© Stack Overflow or respective owner

Related posts about c#

Related posts about excel