C# 自动生成 Excel

发布于 2024-10-13 19:36:15 字数 845 浏览 5 评论 0原文

...

Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;

oXL = new Excel.Application();
oWB = (Excel._Workbook)oXL.ActiveWorkbook;
oSheet = (Excel._Worksheet)oWB.Sheets[1];

oSheet.Cells[5,10] = "Value";

...

在崩溃时产生这个:

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

在这种情况下,第 60 行是

oSheet = (Excel._Worksheet)oWB.Sheets[1];

如果写入该行,也会发生同样的事情

oSheet = (Excel._Worksheet)oWB.ActiveSheet;

此时 Excel 已在屏幕上打开,并带有新的工作表。

...

Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

策马西风 2024-10-20 19:36:15

该错误告诉您 oWB 为空。它为空,因为与从 GUI 打开 Excel 不同,自动化不会创建新的 3 页书。您需要先专门加载一本书,或者添加一本书。

请参阅此处的示例http://support.microsoft.com/kb/302084,其中显式添加了可以使用的新工作簿

    //Get a new workbook.
    oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));

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 ));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文