C# - How to add an Excel Worksheet programmatically - Office XP / 2003 -


i starting fiddle excel via c# able automate creation, , addition excel file.

i can open file , update data , move through existing worksheets. problem how can add new sheets?

i tried:

excel.worksheet newworksheet; newworksheet = (excel.worksheet)excelapp.thisworkbook.worksheets.add(                 type.missing, type.missing, type.missing, type.missing); 

but below com exception , googling has not given me answer.

exception hresult: 0x800a03ec source is: "interop.excel"

i hoping maybe able put me out of misery.

you need add com reference in project "microsoft excel 11.0 object library" - or whatever version appropriate.

this code works me:

private void addworksheettoexcelworkbook(string fullfilename,string worksheetname) {     microsoft.office.interop.excel.application xlapp = null;     workbook xlworkbook = null;     sheets xlsheets = null;     worksheet xlnewsheet = null;      try {         xlapp = new microsoft.office.interop.excel.application();          if (xlapp == null)             return;          // uncomment line below if want see what's happening in excel         // xlapp.visible = true;          xlworkbook = xlapp.workbooks.open(fullfilename, 0, false, 5, "", "",                 false, xlplatform.xlwindows, "",                 true, false, 0, true, false, false);          xlsheets = xlworkbook.sheets sheets;          // first argument below inserts new worksheet first 1         xlnewsheet = (worksheet)xlsheets.add(xlsheets[1], type.missing, type.missing, type.missing);         xlnewsheet.name = worksheetname;          xlworkbook.save();         xlworkbook.close(type.missing,type.missing,type.missing);         xlapp.quit();     }     {         marshal.releasecomobject(xlnewsheet);         marshal.releasecomobject(xlsheets);         marshal.releasecomobject(xlworkbook);         marshal.releasecomobject(xlapp);         xlapp = null;     } } 

note want careful properly cleaning , releasing com object references. included in stackoverflow question useful rule of thumb: "never use 2 dots com objects". in code; you're going have real trouble that. my demo code above not clean excel app, it's start!

some other links found useful when looking question:

according msdn

to use com interop, must have administrator or power user security permissions.

hope helps.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -