Bind to Excel Data Sources
- 2 minutes to read
This document demonstrates how to bind GridControl to data from Microsoft Excel files (XLS, XLSX, or XLSM) or CSV files.
#Reference the Required Assembly
The GridControl uses the ExcelItemsSource class to obtain data from MS Excel files. Reference the DevExpress.Wpf.Core.Extensions NuGet package or the DevExpress.Xpf.Core.v24.1.Extensions assembly in your project to use the ExcelItemsSource class.
#Define the Source
In this example the data source is the Orders.xls file located in the application’s root folder.
Set the file’s Build Action to Resource.
Define the ExcelItemsSource in the resources. Specify the FileUri, StreamDocumentFormat, and WorksheetName properties.
<dx:ThemedWindow.Resources>
<dx:ExcelItemsSource x:Key="ExcelItemsSource"
FileUri="{x:Static local:MainWindow.SourceUri}"
StreamDocumentFormat="Xls"
WorksheetName="Sheet"/>
</dx:ThemedWindow.Resources>
namespace GridControlExcel {
public partial class MainWindow : ThemedWindow {
public static readonly Uri SourceUri = new Uri(@"pack://application:,,,/Orders.xls");
public MainWindow() {
InitializeComponent();
}
}
}
#Specify the Columns
Add columns to the ExcelItemsSource.Columns collection and define their ColumnType.
xmlns:sys="clr-namespace:System;assembly=mscorlib"
...
<dx:ExcelItemsSource x:Key="ExcelItemsSource"
FileUri="{x:Static local:MainWindow.SourceUri}"
StreamDocumentFormat="Xls"
WorksheetName="Sheet">
<dx:ExcelItemsSource.Columns>
<dx:ExcelColumn Name="ID" ColumnType="{x:Type sys:Double}" IsSelected="False" />
<dx:ExcelColumn Name="Product Name" ColumnType="{x:Type sys:String}" />
<dx:ExcelColumn Name="Customer Name" ColumnType="{x:Type sys:String}" />
<dx:ExcelColumn Name="Country" ColumnType="{x:Type sys:String}" />
<dx:ExcelColumn Name="City" ColumnType="{x:Type sys:String}" />
<dx:ExcelColumn Name="Order Date" ColumnType="{x:Type sys:DateTime}" />
<dx:ExcelColumn Name="Unit Price" ColumnType="{x:Type sys:Double}" />
<dx:ExcelColumn Name="Quantity" ColumnType="{x:Type sys:Double}" />
</dx:ExcelItemsSource.Columns>
</dx:ExcelItemsSource>
#Bind the GridControl to Data
Switch to the design view. Invoke the GridControl‘s Quick Actions to specify the ItemsSource:
The following XAML is generated:
<dxg:GridControl ItemsSource="{Binding Path=Data, Source={StaticResource ExcelItemsSource}}"
AutoGenerateColumns="AddNew" />