Question: I have a datagrid which populates a datatable, I want to export the DataTable to excel on click of a button. I am using MVVM for this application. So is it ok to implement the export feature in my view? 

Secondly, as i am using xaml and desktop application, how do i capture the grid and its details.

Can any one suggest me some pointers? I am new to this.

Thanks,
Sagar

Answer: 
This is what i have done and it helped me:

```
private readonly ICommand m_ExportButtonClick;
    private string ExcelFilePath = "";

    public ICommand ExportButtonClick { get { return m_ExportButtonClick; } }

    private void OnRunExport()
    {
        try
        {
            if (queryDatatable == null || queryDatatable.Columns.Count == 0)
                throw new Exception("ExportToExcel: Null or empty input table!\n");

            // load excel, and create a new workbook
            Excell.Application excelApp = new Excell.Application();
            excelApp.Workbooks.Add();

            // single worksheet
            Excell._Worksheet workSheet = excelApp.ActiveSheet;

            // column headings
            for (int i = 0; i < queryDatatable.Columns.Count; i++)
            {
                workSheet.Cells[1, (i + 1)] = queryDatatable.Columns[i].ColumnName;
            }

            // rows
            for (int i = 0; i < queryDatatable.Rows.Count; i++)
            {
                // to do: format datetime values before printing
                for (int j = 0; j < queryDatatable.Columns.Count; j++)
                {
                    workSheet.Cells[(i + 2), (j + 1)] = queryDatatable.Rows[i][j];
                }
            }

            // check fielpath
            if (ExcelFilePath != null && ExcelFilePath != "")
            {
                try
                {                        
                    workSheet.SaveAs(ExcelFilePath);
                    excelApp.Quit();
                    MessageBox.Show("Excel file saved!");
                }
                catch (Exception ex)
                {
                    throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                        + ex.Message);
                }
            }
            else    // no filepath is given, the file opens up and the user can save it accordingly.
            {
                excelApp.Visible = true;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("There is no data to export. Please check your query/ Contact administrator." + ex.Message);
        }
    }      
    #endregion

```
Try googling around a little. This is a very common problem and has been asked a lot already. Here's a good answer from this [SO question](https://stackoverflow.com/questions/3283204/convert-datatable-to-excel-2007-xlsx)

```cs
public static void ExportToExcel<T>(IEnumerable<T> exportData)
{
    Excel.ApplicationClass excel = new Excel.ApplicationClass();
    Excel.Workbook workbook = excel.Application.Workbooks.Add(true);
    PropertyInfo[] pInfos = typeof(T).GetProperties();
    if (pInfos != null && pInfos.Count() > 0)
    {
        int iCol = 0;
        int iRow = 0;
        foreach (PropertyInfo eachPInfo in pInfos.Where(W => 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 => 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();
    }
}

```