Export Data From DataGrid to Excel Sheet in WPF

Introduction

This article describes exporting a DataGrid cell value to an Excel sheet. It is very easy to do that, you just need to use a small procedure. In this article I have used the Microsoft.Office.Interop.Excel namespace to export data. Microsoft.Office.Interop.Excel is a namespace provided with Visual Studio 2005 and later.

The namespace Microsoft.Office.Interop.Excel is already integrated into Visual Studio, to use the namespace you need to provide a reference for this namespace. Use the following procedure to get a reference of the namespace.

  1. Right-click on your application
  2. Go to Add Reference and click on that.
  3. The Reference Manager window will open, select Framework from the left side panel and select Microsoft.Office.Interop.Excel from the listbox.

Getting Started

  1. Fill in the DataGrid with items
  2. Create an object of Excel application
  3. Create an object of Workbook
  4. Create an object of WorkSheet
  5. Create header of WorkSheet
  6. Insert data into the cell
  7. Save and close the Excel application and remove COM references

1. Fill DataGrid

Take a DataGrid control from the Tools panel and set the item's Source to what you are going to export.

2. Create an Object Of Excel Application

Create an object of the Application class in the Microsoft.Office.Interop.Excel namespace as in the following:

public Microsoft.Office.Interop.Excel.Application APP= new Microsoft.Office.Interop.Excel.Application();

3. Create an object of Workbook.

Using the WorkBook class, create a WorkBook object containing a worksheet and assign a workbook from the Application object to this object.

public Microsoft.Office.Interop.Excel.Workbook WB =  APP.Workbooks.Add(1);

4. Create an object of WorkSheet.

Create an object of the WorkSheet class and again assign a worksheet from the workbook object created above to this worksheet object, here I assigned the first worksheet to this object.

this.WS = (Microsoft.Office.Interop.Excel.Worksheet)WB.Sheets[1]; 

5. Create a header of WorkSheet

Retrieve all the column headers from the DataGrid to create headers of the Excel Sheet. Using LINQ you can retrieve header text from the DataGrid Control. List all header text and use a for loop to set the header as in the following code.

int ind=1;

foreach (object ob in this.dgvFields.Columns.Select(cs => cs.Header).ToList())

{   

      this.WS.Cells[1, ind] = ob.ToStrihng();

      ind++; 

}

6. Insert Data into Cell

As in the code above, using a foreach loop retrieve all the items of the datagrid from the itemsource and insert it into the Excel sheet cells one by one, but here the data insertion starts from the second row.

ind= 2;
foreach (Field field in dgvFields.ItemsSource)
{
DataRow DR = DRV.Row;
for (int ind1 = 1; ind1 <= dgvFields.Columns.Count; ind1++)
{
WS.Cells[ind][ind1] = DR[ind1 - 1];
}
ind++;
}

7. Save and close Excel application and remove COM references

After inserting data to the Excel cells, save the Excel application, close and remove COM objects from the process, you can remove the objects using the Marshal class. See the code below.

if (this.APP.ActiveWorkbook != null)

this.APP.ActiveWorkbook.Save();

if (this.APP != null)

{

  if (this.WB != null)

  {

       if (this.WS != null)

        Marshal.ReleaseComObject(this.WS);

        this.WB.Close(false, Type.Missing, Type.Missing);

        Marshal.ReleaseComObject(this.WB);

    }

    this.APP.Quit();

    Marshal.ReleaseComObject(this.APP);

}

 
Full Code
-------------
XAML
--------
  1. <DataGrid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Name="dgvFields" Margin="0,50,0,0" CanUserAddRows="False" IsReadOnly="True" AutoGenerateColumns="False" GridLinesVisibility="None" InitializingNewItem="dgvMarket_InitializingNewItem">  
  2.             <DataGrid.Columns>  
  3.                 <DataGridTextColumn Binding="{Binding Path=Excenge}" Header="EXCHANGE" Width="70">  
  4.                     <DataGridTextColumn.CellStyle>  
  5.                         <Style TargetType="DataGridCell">  
  6.                             <Setter Property="Background" Value="Black" />  
  7.                             <Setter Property="Foreground" Value="White" />  
  8.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  9.                             <Setter Property="FontSize" Value="14"></Setter>  
  10.                         </Style>  
  11.                     </DataGridTextColumn.CellStyle>  
  12.                 </DataGridTextColumn>  
  13.                 <DataGridTextColumn Binding="{Binding Path=Symbol}" Header="Symbol" Width="50">  
  14.                     <DataGridTextColumn.CellStyle>  
  15.                         <Style TargetType="DataGridCell">  
  16.                             <Setter Property="Background" Value="Black" />  
  17.                             <Setter Property="Foreground" Value="White" />  
  18.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  19.                             <Setter Property="FontSize" Value="14"></Setter>  
  20.                         </Style>  
  21.                     </DataGridTextColumn.CellStyle>  
  22.                 </DataGridTextColumn>  
  23.                 <DataGridTextColumn Binding="{Binding Path=EXP}" Header="EXP" Width="100">  
  24.                     <DataGridTextColumn.CellStyle>  
  25.                         <Style TargetType="DataGridCell">  
  26.                             <Setter Property="Background" Value="Black" />  
  27.                             <Setter Property="Foreground" Value="White" />  
  28.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  29.                             <Setter Property="FontSize" Value="14"></Setter>  
  30.                         </Style>  
  31.                     </DataGridTextColumn.CellStyle>  
  32.                 </DataGridTextColumn>  
  33.                 <DataGridTextColumn Binding="{Binding Path=NetChange}"  Header="Net Change" Width="100">  
  34.                     <DataGridTextColumn.CellStyle>  
  35.                         <Style TargetType="DataGridCell">  
  36.                             <Setter Property="Background" Value="{Binding ColorNetChange}" />  
  37.                             <Setter Property="Foreground" Value="White" />  
  38.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  39.                             <Setter Property="FontSize" Value="14"></Setter>  
  40.                         </Style>  
  41.                     </DataGridTextColumn.CellStyle>  
  42.                 </DataGridTextColumn>  
  43.                 <DataGridTextColumn Binding="{Binding Path=BSZ}"  Header="BSZ" Width="100">  
  44.                     <DataGridTextColumn.CellStyle>  
  45.                         <Style TargetType="DataGridCell">  
  46.                             <Setter Property="Background" Value="{Binding ColorBSZ}" />  
  47.                             <Setter Property="Foreground" Value="White" />  
  48.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  49.                             <Setter Property="FontSize" Value="14"></Setter>  
  50.                         </Style>  
  51.                     </DataGridTextColumn.CellStyle>  
  52.                 </DataGridTextColumn>  
  53.                 <DataGridTextColumn Binding="{Binding Path=BID}"  Header="BID" Width="120">  
  54.                     <DataGridTextColumn.CellStyle>  
  55.                         <Style TargetType="DataGridCell">  
  56.                             <Setter Property="Background" Value="{Binding ColorBID}" />  
  57.                             <Setter Property="Foreground" Value="White" />  
  58.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  59.                             <Setter Property="FontSize" Value="14"></Setter>  
  60.                         </Style>  
  61.                     </DataGridTextColumn.CellStyle>  
  62.                 </DataGridTextColumn>  
  63.                 <DataGridTextColumn Binding="{Binding Path=ASK}"  Header="ASK" Width="120">  
  64.                     <DataGridTextColumn.CellStyle>  
  65.                         <Style TargetType="DataGridCell">  
  66.                             <Setter Property="Background" Value="{Binding ColorASK}" />  
  67.                             <Setter Property="Foreground" Value="White" />  
  68.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  69.                             <Setter Property="FontSize" Value="14"></Setter>  
  70.                         </Style>  
  71.                     </DataGridTextColumn.CellStyle>  
  72.                 </DataGridTextColumn>  
  73.                 <DataGridTextColumn Binding="{Binding Path=ASZ}"  Header="ASZ" Width="120">  
  74.                     <DataGridTextColumn.CellStyle>  
  75.                         <Style TargetType="DataGridCell">  
  76.                             <Setter Property="Background" Value="{Binding ColorASZ}" />  
  77.                             <Setter Property="Foreground" Value="White" />  
  78.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  79.                             <Setter Property="FontSize" Value="14"></Setter>  
  80.                         </Style>  
  81.                     </DataGridTextColumn.CellStyle>  
  82.                 </DataGridTextColumn>  
  83.                 <DataGridTextColumn Binding="{Binding Path=OPEN}"  Header="OPEN" Width="120">  
  84.                     <DataGridTextColumn.CellStyle>  
  85.                         <Style TargetType="DataGridCell">  
  86.                             <Setter Property="Background" Value="{Binding ColorOPEN}" />  
  87.                             <Setter Property="Foreground" Value="White" />  
  88.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  89.                             <Setter Property="FontSize" Value="14"></Setter>  
  90.                         </Style>  
  91.                     </DataGridTextColumn.CellStyle>  
  92.                 </DataGridTextColumn>  
  93.                 <DataGridTextColumn Binding="{Binding Path=HIGH}"  Header="HIGH" Width="120">  
  94.                     <DataGridTextColumn.CellStyle>  
  95.                         <Style TargetType="DataGridCell">  
  96.                             <Setter Property="Background" Value="{Binding ColorHIGH}" />  
  97.                             <Setter Property="Foreground" Value="White" />  
  98.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  99.                             <Setter Property="FontSize" Value="14"></Setter>  
  100.                         </Style>  
  101.                     </DataGridTextColumn.CellStyle>  
  102.                 </DataGridTextColumn>  
  103.                 <DataGridTextColumn Binding="{Binding Path=LOW}"  Header="LOW" Width="120">  
  104.                     <DataGridTextColumn.CellStyle>  
  105.                         <Style TargetType="DataGridCell">  
  106.                             <Setter Property="Background" Value="{Binding ColorLOW}" />  
  107.                             <Setter Property="Foreground" Value="White" />  
  108.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  109.                             <Setter Property="FontSize" Value="14"></Setter>  
  110.                         </Style>  
  111.                     </DataGridTextColumn.CellStyle>  
  112.                 </DataGridTextColumn>  
  113.                 <DataGridTextColumn Binding="{Binding Path=CLOSE}"  Header="CLOSE" Width="120">  
  114.                     <DataGridTextColumn.CellStyle>  
  115.                         <Style TargetType="DataGridCell">  
  116.                             <Setter Property="Background" Value="{Binding ColorCLOSE}" />  
  117.                             <Setter Property="Foreground" Value="White" />  
  118.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  119.                             <Setter Property="FontSize" Value="14"></Setter>  
  120.                         </Style>  
  121.                     </DataGridTextColumn.CellStyle>  
  122.                 </DataGridTextColumn>  
  123.                 <DataGridTextColumn Binding="{Binding Path=CHANGE}"  Header="% CHANGE" Width="120">  
  124.                     <DataGridTextColumn.CellStyle>  
  125.                         <Style TargetType="DataGridCell">  
  126.                             <Setter Property="Background" Value="{Binding ColorCHANGE}" />  
  127.                             <Setter Property="Foreground" Value="White" />  
  128.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  129.                             <Setter Property="FontSize" Value="14"></Setter>  
  130.                         </Style>  
  131.                     </DataGridTextColumn.CellStyle>  
  132.                 </DataGridTextColumn>  
  133.                 <DataGridTextColumn Binding="{Binding Path=SETTLEMENT}"  Header="SETTLEMENT" Width="120">  
  134.                     <DataGridTextColumn.CellStyle>  
  135.                         <Style TargetType="DataGridCell">  
  136.                             <Setter Property="Background" Value="Black" />  
  137.                             <Setter Property="Foreground" Value="White" />  
  138.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  139.                             <Setter Property="FontSize" Value="14"></Setter>  
  140.                         </Style>  
  141.                     </DataGridTextColumn.CellStyle>  
  142.                 </DataGridTextColumn>  
  143.                 <DataGridTextColumn Binding="{Binding Path=VOL}"  Header="VOL." Width="120">  
  144.                     <DataGridTextColumn.CellStyle>  
  145.                         <Style TargetType="DataGridCell">  
  146.                             <Setter Property="Background" Value="{Binding ColorVOL}" />  
  147.                             <Setter Property="Foreground" Value="White" />  
  148.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  149.                             <Setter Property="FontSize" Value="14"></Setter>  
  150.                         </Style>  
  151.                     </DataGridTextColumn.CellStyle>  
  152.                 </DataGridTextColumn>  
  153.                 <DataGridTextColumn Binding="{Binding Path=OpInt}"  Header="Op. Int." Width="120">  
  154.                     <DataGridTextColumn.CellStyle>  
  155.                         <Style TargetType="DataGridCell">  
  156.                             <Setter Property="Background" Value="{Binding ColorOpInt}" />  
  157.                             <Setter Property="Foreground" Value="White" />  
  158.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  159.                             <Setter Property="FontSize" Value="14"></Setter>  
  160.                         </Style>  
  161.                     </DataGridTextColumn.CellStyle>  
  162.                 </DataGridTextColumn>  
  163.                 <DataGridTextColumn Binding="{Binding Path=OBOS}"  Header="OB OS" Width="120">  
  164.                     <DataGridTextColumn.CellStyle>  
  165.                         <Style TargetType="DataGridCell">  
  166.                             <Setter Property="Background" Value="Black" />  
  167.                             <Setter Property="Foreground" Value="White" />  
  168.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  169.                             <Setter Property="FontSize" Value="14"></Setter>  
  170.                         </Style>  
  171.                     </DataGridTextColumn.CellStyle>  
  172.                 </DataGridTextColumn>  
  173.                 <DataGridTextColumn Binding="{Binding Path=LSZ}"  Header="LSZ" Width="120">  
  174.                     <DataGridTextColumn.CellStyle>  
  175.                         <Style TargetType="DataGridCell">  
  176.                             <Setter Property="Background" Value="Black" />  
  177.                             <Setter Property="Foreground" Value="White" />  
  178.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  179.                             <Setter Property="FontSize" Value="14"></Setter>  
  180.                         </Style>  
  181.                     </DataGridTextColumn.CellStyle>  
  182.                 </DataGridTextColumn>  
  183.                 <DataGridTextColumn Binding="{Binding Path=Code}"  Header="Code" Width="120">  
  184.                     <DataGridTextColumn.CellStyle>  
  185.                         <Style TargetType="DataGridCell">  
  186.                             <Setter Property="Background" Value="Black" />  
  187.                             <Setter Property="Foreground" Value="White" />  
  188.                             <Setter Property="FontWeight" Value="Bold"></Setter>  
  189.                             <Setter Property="FontSize" Value="14"></Setter>  
  190.                         </Style>  
  191.                     </DataGridTextColumn.CellStyle>  
  192.                 </DataGridTextColumn>  
  193.             </DataGrid.Columns>  
  194.             <DataGrid.ContextMenu>  
  195.                 <ContextMenu>  
  196.                     <MenuItem Header="Export" Click="Button_Click_1">  
  197.                     </MenuItem>  
  198.                 </ContextMenu>  
  199.             </DataGrid.ContextMenu>  
  200.         </DataGrid>  
 C# Code
 ------------
  1. public class MyExcel  
  2.    {  
  3.        public Microsoft.Office.Interop.Excel.Application APP = null;  
  4.        public Microsoft.Office.Interop.Excel.Workbook WB = null;  
  5.        public Microsoft.Office.Interop.Excel.Worksheet WS = null;  
  6.        public Microsoft.Office.Interop.Excel.Range Range = null;  
  7.   
  8.     public MyExcel()  
  9.       {  
  10.           this.APP = new Microsoft.Office.Interop.Excel.Application();     
  11.    this.Open("C:\\MyExcel.xlsx","Sheet1");  
  12.    this.CreateHeader();     
  13.    this.InsertDate()   
  14.    this.Close();      
  15.       }  
  16.   
  17. private void Open(string Location, int workSheet)  
  18.       {  
  19.          this.WB= this.APP.Workbooks.Open(Location);  
  20.          this.WS = (Microsoft.Office.Interop.Excel.Worksheet)WB.Sheets[workSheet];  
  21.          return this.WS;  
  22.       }  
  23. private void CreateHeader()  
  24. {  
  25.     int ind=1;  
  26.     foreach (object ob in this.dgvFields.Columns.Select(cs => cs.Header).ToList())  
  27.     {     
  28.                 this.WS.Cells[1, ind] = ob.ToStrihng();  
  29.                 ind++;   
  30.     }  
  31. }  
  32. private void InsertData()  
  33. {  
  34.     ind= 2;  
  35.     foreach (Field field in dgvFields.ItemsSource)  
  36.     {  
  37.                 DataRow DR = DRV.Row;  
  38.                 for (int ind1 = 1; ind1 <= dgvFields.Columns.Count; ind1++)  
  39.                 {  
  40.                 WS.Cells[ind][ind1] = DR[ind1 - 1];  
  41.                 }  
  42.                 ind++;  
  43.     }   
  44. }  
  45. private void Close()  
  46. {  
  47.     if (this.APP.ActiveWorkbook != null)  
  48.     this.APP.ActiveWorkbook.Save();  
  49.     if (this.APP != null)  
  50.     {  
  51.             if (this.WB != null)  
  52.             {  
  53.                     if (this.WS != null)  
  54.                     Marshal.ReleaseComObject(this.WS);  
  55.                 this.WB.Close(false, Type.Missing, Type.Missing);  
  56.                 Marshal.ReleaseComObject(this.WB);  
  57.             }  
  58.             this.APP.Quit();  
  59.             Marshal.ReleaseComObject(this.APP);  
  60.     }  
  61. }   
 

Conclusion

In this article we learn how to export data from a WPF Data Grid to a Microsoft Excel Sheet using the namespace Microsoft.Office.Interop.Excel.