I also searched for something simillar to help export data to datagrid in excel, but didn't find anything that works. Atlast I just converted the contents of the DataGrid to a two-dimensional array of rows and exported it using dll interop.
The code looks something like this:
Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; Excel.Range rangeToHoldHyperlink; Excel.Range CellInstance; xlApp = new Excel.Application(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); xlApp.DisplayAlerts = false; //Dummy initialisation to prevent errors. rangeToHoldHyperlink = xlWorkSheet.get_Range("A1", Type.Missing); CellInstance = xlWorkSheet.get_Range("A1", Type.Missing); for (int i = 0; i < NumberOfCols; i++) { for (int j = 0; j <= NumberOfRows; j++) { xlWorkSheet.Cells[j + 1, i + 1] = DataToWrite[j][i]; } }
If you are looking for some form, they are also supported in this. I wanted to add a hyperlink, and the following code does this:
CellInstance = xlWorkSheet.Cells[j + 1, i + 1]; xlWorkSheet.Hyperlinks.Add( CellInstance, DataToWrite[j][i], Type.Missing, "Hover Text Comes Here", "Text to be displayed");
If you want the first line to be the headline, you can select them as follows:
Excel.Range Range1 = xlWorkSheet.get_Range("A1"); Range1.EntireRow.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black); Range1.EntireRow.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightSkyBlue); Range1.EntireRow.Font.Size = 14; Range1.EntireRow.AutoFit();
Finally, to save excel along the desired path:
xlWorkBook.SaveAs(@FilePath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); xlWorkBook.Close();
The interop link is added as follows:
Right Click on the Project name -> Click "Add reference" -> Goto "COM" tab -> Search for "Microsoft Excel Object Library" click "OK" to add the reference.
You must use the following namespace:
using Excel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices;