1

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!

2
  • I would like to inform you on this: If the application you are working will be used without someone attending it at all times (e.g. a server), you will eventually run into problems. Microsoft doesn't suggest it. support.microsoft.com/kb/257757 Commented Mar 15, 2013 at 5:37
  • Thank you for your input, but the program will be run by users as needed, no automation. Commented Mar 15, 2013 at 13:28

2 Answers 2

2

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:

  • Release every object with System.Runtime.InteropServices.Marshal.ReleaseComObject(object) when you're finished with it. If you don't, Excel won't exit when you're done.
  • Don't use double-dot references (i.e., object1.object2.value). If you do you can't release it properly as above.
  • Indexes always start from 1, not 0 (in my experience anyway).
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the "two dots" rule. It's worth noting that all references can also be set to null, which will help with garbage collection.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.