wpf中datagrid和excel绑定的代码
时间: 2023-05-28 13:03:47 浏览: 140
以下是WPF中DataGrid和Excel绑定的代码示例。
首先,需要在XAML文件中添加DataGrid控件:
```xml
<DataGrid x:Name="myDataGrid" ItemsSource="{Binding}">
<DataGrid.Columns>
<DataGridTextColumn Header="姓名" Binding="{Binding Name}" />
<DataGridTextColumn Header="年龄" Binding="{Binding Age}" />
<DataGridTextColumn Header="性别" Binding="{Binding Gender}" />
</DataGrid.Columns>
</DataGrid>
```
然后,在C#代码中,需要添加以下引用:
```csharp
using Excel = Microsoft.Office.Interop.Excel;
```
接着,需要定义一个类来存储Excel中的数据:
```csharp
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
```
然后,需要添加以下代码来读取Excel文件中的数据:
```csharp
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Open(@"C:\path\to\your\excel\file.xlsx");
Excel.Worksheet worksheet = workbook.Sheets[1];
Excel.Range range = worksheet.UsedRange;
List<Person> people = new List<Person>();
for (int row = 2; row <= range.Rows.Count; row++)
{
Person person = new Person();
person.Name = Convert.ToString((range.Cells[row, 1] as Excel.Range).Value2);
person.Age = Convert.ToInt32((range.Cells[row, 2] as Excel.Range).Value2);
person.Gender = Convert.ToString((range.Cells[row, 3] as Excel.Range).Value2);
people.Add(person);
}
myDataGrid.ItemsSource = people;
```
最后,需要记得在程序结束时关闭Excel应用程序:
```csharp
workbook.Close();
excelApp.Quit();
```
阅读全文