C# Automating to Excel
...
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Work开发者_高级运维sheet oSheet;
oXL = new Excel.Application();
oWB = (Excel._Workbook)oXL.ActiveWorkbook;
oSheet = (Excel._Worksheet)oWB.Sheets[1];
oSheet.Cells[5,10] = "Value";
...
yields this at crash:
Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
at ConsoleApplication1.Program.Main(String[] args) in C:\Wherever\Visual Studio 2008\Projects\ConsoleApplication20\ConsoleApplication20\Program.
cs:line 60
In this case, line 60 is
oSheet = (Excel._Worksheet)oWB.Sheets[1];
and the same thing happens if the line is written
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
.
Excel is already open onscreen at the time, with a fresh worksheet in place.
The error is telling you that oWB is null. It is null because unlike opening Excel from a GUI, automation does not create a new 3-sheet book. You need to specifically load a book first, or add one.
See example here http://support.microsoft.com/kb/302084 where it explicitly adds a new workbook to play with
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));
精彩评论