tags:

views:

150

answers:

4

I want to know what is the best practice to create a Excel 2007 Workbook using C#, with its datasource being a raw flat file or a table in database.

A: 

I personally like creating CSV's, which can be opened directly in Excel. It's a lot less work than trying to hack the Office Open XML specification, and you don't need COM interop to Excel (which requires a copy of Excel to work).

Robert Harvey
But there are some problems with using CSVs to open in Excel. For instance if you want to put a comma, double-quote or new line, they need to be encoded. Another thing is when you want to output a string that has a number format and starts with "0" If you want the `01` to appear in the excel cell. You can't output it directly because excel thinks it's a number and remove the `0` Then you have to put a formula in your CSV something like `="01"` And to scape this into CSV you have to write it like this: `"=""01"""`. And to scape this in c#: `@"""=""""01"""""""`.
Carlos Muñoz
A: 

You can use the Office Primary Interop Assemblies to completely automate Excel 2007, and create the workbook from within C#.

This gives you the most control, as you have complete control over how you map from DB or flat file -> Excel workbook/worksheet.

Reed Copsey
+2  A: 

You can use

"Open XML SDK 2.0 for Microsoft Office"

It's more comfortable than harcore manually hacking OpenXML spec. There are .NET strongly typed wrapper classes so it's not hard to create a simple sheet. You don't need any interop and msoffice installed and it's safe for server soluitions - there are only a few dlls which you can ship in your solution.

I did mail-merge solution and it wasn't so scary.

But as always, when it's possible, I'm prefering plain csv format.

tomo
A: 

I am using http://www.leniel.net/2009/07/creating-excel-spreadsheets-xls-xlsx-c.html for creating excel . Seems good so far.

Subbarao