Reputation: 163
I am working on a project that runs MySQL queries on DB. I need to feed out the results to a excel sheet that I will be generating on the fly. I had started the code, using msdn tutorials as well as information I found on stackoverflow, however running the application leaves me with
"Object reference not set to an instance of an object."
At this point I just have the basic code started as I wanted to make this work before I started creating the entire spreadsheet in the code.
var excelApp = new Excel.Application();
excelApp.Visible = true;
Excel.Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
((Excel.Range)workSheet.Cells[1, 1]).Value = "Print Date:";
If I can provide any more info just ask. I greatly appreciate any information or insight you can provide me with!
Upvotes: 1
Views: 395
Reputation: 71
The reason you get that error is, you have not created any worksheets in the Application. Try doing this.
Excel.Worksheet newWorksheet;
newWorksheet = (Excel.Worksheet)excelApp.Worksheets.Add();
Upvotes: 0
Reputation: 840
I'd say that workSheet
is being set to null as excelApp.ActiveSheet
doesn't exist yet.
Here's some code that'll create a worksheet object you can use...
var application = new Application();
var workbooks = application.Workbooks;
var workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
var worksheets = (Sheets)workbook.Worksheets;
var worksheet = worksheets[1];
A few things to note when working with Excel:
System.Runtime.InteropServices.Marshal.ReleaseComObject(object)
when you're finished with it. If you don't, Excel won't exit when you're done.Upvotes: 2