Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I wrote the following code for the company some time back. It takes Enumerable of any class type and exports all its (get)properties to Excel and also open Excel. You should be able to do something similar for a DataTable. Remember you need to add reference to Microsoft.Office.Interop.Excel</p> <pre><code> public static void ExportToExcel&lt;T&gt;(IEnumerable&lt;T&gt; exportData) { Excel.ApplicationClass excel = new Excel.ApplicationClass(); Excel.Workbook workbook = excel.Application.Workbooks.Add(true); PropertyInfo[] pInfos = typeof(T).GetProperties(); if (pInfos != null &amp;&amp; pInfos.Count() &gt; 0) { int iCol = 0; int iRow = 0; foreach (PropertyInfo eachPInfo in pInfos.Where(W =&gt; W.CanRead == true)) { // Add column headings... iCol++; excel.Cells[1, iCol] = eachPInfo.Name; } foreach (T item in exportData) { iRow++; // add each row's cell data... iCol = 0; foreach (PropertyInfo eachPInfo in pInfos.Where(W =&gt; W.CanRead == true)) { iCol++; excel.Cells[iRow + 1, iCol] = eachPInfo.GetValue(item, null); } } // Global missing reference for objects we are not defining... object missing = System.Reflection.Missing.Value; // If wanting to Save the workbook... string filePath = System.IO.Path.GetTempPath() + DateTime.Now.Ticks.ToString() + ".xlsm"; workbook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled, missing, missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing); // If wanting to make Excel visible and activate the worksheet... excel.Visible = true; Excel.Worksheet worksheet = (Excel.Worksheet)excel.ActiveSheet; excel.Rows.EntireRow.AutoFit(); excel.Columns.EntireColumn.AutoFit(); ((Excel._Worksheet)worksheet).Activate(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload