C # Automatizzare Excel
-
24-10-2019 - |
Domanda
...
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";
...
cede a questo incidente:
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 questo caso, la linea 60 è
oSheet = (Excel._Worksheet)oWB.Sheets[1];
e la stessa cosa accade se la linea è scritto
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
.
Excel è già aperto sullo schermo, al momento, con un foglio di lavoro fresco sul posto.
Soluzione
L'errore è che si dice che OWB è nullo. Si è nullo perché a differenza di apertura di Excel da una GUI, l'automazione non creare un nuovo prenota 3 fogli. È necessario caricare specificamente un libro prima, o aggiungere uno.
Si veda l'esempio qui http://support.microsoft.com/kb/302084 dove aggiunge in modo esplicito una nuova cartella di lavoro per giocare con
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow