簡體   English   中英

如何在c#中將excel值設置為datagrid?

[英]How to set excel value to datagrid in c#?

xmal.c

  <StackPanel HorizontalAlignment="Left" Height="337" VerticalAlignment="Top" Width="514" Margin="103,39,0,0">
            <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Source=Lecturers}" >
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                    <DataGridTextColumn Header="Surname" Binding="{Binding Surname}"/>
                    <DataGridTextColumn Header="Phone" Binding="{Binding Phone_Number}" />
                </DataGrid.Columns>
            </DataGrid>
        </StackPanel>

Excel行和列:

Name   Surname   Phone_Number

A        C           123

C        C           124

嗨。我在Excel中獲得了值。 它以同樣的方式出現。 但是當我想設置datagrid時,我無法做到這一點。 我如何設置datagrid? 使用Excel計算相同的數據網格行。

 **Lecturers.DataSource=cellvalue** 

這一行使用set datagrid。 但是我沒有設置datagrid。

首先創建一個代表您的數據的類

    public class Lecturer
    {
       public string Name { get; set;}

       public string Surname { get; set;}

       public int Phone_Number { get; set;}
    }

然后在ViewModel中,聲明一個ObservableCollection,您可以在其中存儲Read對象。 ObservableCollection實現了INotifyPropertyChanged接口,該接口將允許您的視圖通知ViewModel中的數據更改。

[...]

public ObservableCollection<Lecturer> Lecturers { get; set; }

public MyViewModel()
{
  Lecturers = new ObservableCollection<Lecturer>();
}

public void ExtractLecturersFromXlFile(string filePath)
{
 Excel.Application xlApp = new Excel.Application();
 Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filePath);
 Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];

 Excel.Range range = sheet.UsedRange;
 Excel.Range excelrange = (Excel.Range)sheet.get_Range("A1:C100",Type.Missing);

 // Iterate through datas, fill Lecturer's object and add it to the Observable                 
 // Collection


 // Cleanup  
 GC.Collect();
 GC.WaitForPendingFinalizers();

 Marshal.ReleaseComObject(xlWorksheet);

 // Close and release  
 xlWorkbook.Close();
 Marshal.ReleaseComObject(xlWorkbook);

 // Quit and release  
 xlApp.Quit();
 Marshal.ReleaseComObject(xlApp);

}

而在XAML中

     <StackPanel HorizontalAlignment="Left" Height="337" VerticalAlignment="Top"                   Width="514" Margin="103,39,0,0">
        <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Lecturers}" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="Surname" Binding="{Binding Surname}"/>
                <DataGridTextColumn Header="Phone" Binding="{Binding Phone_Number}" />
            </DataGrid.Columns>
        </DataGrid>
    </StackPanel>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM