开发者

C# Automating to Excel

开发者 https://www.devze.com 2023-02-06 06:52 出处:网络
... Excel.Application oXL; Excel._Workbook oWB; Excel._Work开发者_高级运维sheet oSheet; oXL = new Excel.Application();

...

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 ));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号