The ExcelDataSource allows you to specify its schema using the ExcelDataSource.Schema property that provides access to a collection of FieldInfo objects. The FieldInfo class exposes the Name and Type properties allowing you to specify the field name and type, respectively. The Selected property specifies whether or not the field will be displayed within the field list.

Example
This example shows how to customize the schema of the ExcelDataSource using the ExcelDataSource.Schema property. To do this, perform the following steps.
C# |
ExcelDataSource excelDataSource = new ExcelDataSource();
excelDataSource.Name = "Excel Data Source";
excelDataSource.FileName = HostingEnvironment.MapPath(@"~/App_Data/ExcelDataSource.xlsx");
ExcelWorksheetSettings worksheetSettings = new ExcelWorksheetSettings("SalesPerson", "A1:L2000");
excelDataSource.SourceOptions = new ExcelSourceOptions(worksheetSettings);
IExcelSchemaProvider schemaProvider = excelDataSource.GetService(typeof(IExcelSchemaProvider))
as IExcelSchemaProvider;
FieldInfo[] availableFields = schemaProvider.GetSchema(excelDataSource.FileName, null,
ExcelDocumentFormat.Xlsx, excelDataSource.SourceOptions, System.Threading.CancellationToken.None);
List<string> fieldsToSelect = new List<string>() { "CategoryName", "ProductName", "Country", "Quantity",
"Extended Price"};
foreach (FieldInfo field in availableFields) {
if (fieldsToSelect.Contains(field.Name)) {
excelDataSource.Schema.Add(field);
}
else {
field.Selected = false;
excelDataSource.Schema.Add(field);
}
}
excelDataSource.Fill();
|
VB |
Dim excelDataSource As New ExcelDataSource()
excelDataSource.Name = "Excel Data Source"
excelDataSource.FileName = HostingEnvironment.MapPath("~/App_Data/ExcelDataSource.xlsx")
Dim worksheetSettings As New ExcelWorksheetSettings("SalesPerson", "A1:L2000")
excelDataSource.SourceOptions = New ExcelSourceOptions(worksheetSettings)
Dim schemaProvider As IExcelSchemaProvider = TryCast(excelDataSource.GetService(GetType(IExcelSchemaProvider)), IExcelSchemaProvider)
Dim availableFields() As FieldInfo = schemaProvider.GetSchema(excelDataSource.FileName, Nothing, ExcelDocumentFormat.Xlsx, excelDataSource.SourceOptions, System.Threading.CancellationToken.None)
Dim fieldsToSelect As New List(Of String) (New String() {"CategoryName", "ProductName", "Country", "Quantity", "Extended Price"})
For Each field As FieldInfo In availableFields
If fieldsToSelect.Contains(field.Name) Then
excelDataSource.Schema.Add(field)
Else
field.Selected = False
excelDataSource.Schema.Add(field)
End If
Next field
excelDataSource.Fill()
|