eknofsky
eknofsky

Reputation: 163

C# generating excel file and writing to cells

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

Answers (2)

Ankur Singhal
Ankur Singhal

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

MrBlue
MrBlue

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:

  • 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).

Upvotes: 2

Related Questions