views:

2144

answers:

3

I am trying to send some data from a LINQ query in C# to an Excel speed sheet using OLE

I have a query like this:

Var data = from d in db.{MyTable}
           where d.Name = "Test"
           select d;

I have the Excel OLE object working fine, I just can't figure out how to populate the cells in Excel with the data from the LINQ query.

PS: I am using Excel 2003 if that makes any difference.

Can anyone help me with this?

A: 

I assume you are not using OLE in a web scenario, because it will eventually fail.

If you just need raw data, you can dump to a tab-delimited textfile:

var lines = data.Select(d => d.Name + '\t' + d.AnotherProperty + ...);

ifwdev
A: 

Your best option is using the Excel XML format. I did a blog post on how to achieve that: http://www.aaron-powell.com/blog.aspx?id=1237

You're other option would be looking at the LINQ provider for Excel - http://www.codeplex.com/xlslinq.

Slace
He mentioned he is using 2003 not 2007
Ray Booysen
And that makes a difference how? I'm not refering to Open XML in my blog post, which is supported in Office 2003, but the Excel XML markup, which has been supported from prior to Office 2003.
Slace
+2  A: 

Sending individual OLE commands for each Excel cell is very slow so the key is to create an object array like this:

int noOfRows = data.Count - 1;
int noOfColumns = mydataclass.GetType().GetProperties().Count() - 1;
Object[noOfRows, noOfColumns] myArray;

Sending an object array allows you to send a mixture of data types e.g. string, integer, date etc. However, if you know that the data is all text for example, you can just send a string array.

The array needs to be populated from the query either by assigning each individual value or perhaps by using reflection to get the data object properties. Then you can send the array to Excel like this:

XLOLESheetobj.Range("A1","Z20").Value = myArray;

You can substitute Z20 with the number of columns -> Char + the number of rows -> string.

Damien