WPF 读取Excel数据到listview中显示

2025-10-25 08:10:19

1、新建一个listview

2、代码如下:

 <ListView  Name="listExcel" Height="250" Margin="10,10,0,0" Grid.ColumnSpan="3" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Left"    VerticalAlignment="Top

            <ListView.View>

                <GridView  >

                    <GridViewColumn  Width="100" Header="Name" DisplayMemberBinding="{Binding Name}" />

                    <GridViewColumn Width="100" Header="Age" DisplayMemberBinding="{Binding Age}"/>

                    <GridViewColumn Width="100" Header="Sex" DisplayMemberBinding="{Binding Sex}"  >

                        <GridViewColumn.HeaderTemplate>

                            <DataTemplate>

                                <TextBlock  Text="{Binding}"  Foreground="Red"/>

                            </DataTemplate>

                        </GridViewColumn.HeaderTemplate>

                    </GridViewColumn>

                    <GridViewColumn Width="200" Header="Add" DisplayMemberBinding="{Binding Add}" />

                </GridView>

            </ListView.View>

        </ListView>

需要Bing 对应的header名字,这个名字也需要和Excel中的header名字对应,否则无法进行读取显示

3、后台代码如下:

string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0;Data Source=" + path;

                System.Data.OleDb.OleDbConnection oledbconn = new System.Data.OleDb.OleDbConnection(connStr);

                oledbconn.Open();

                System.Data.DataTable _table = oledbconn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

                string strTableName = string.Empty;

                if (_table.Rows.Count > 0)

                {

                    strTableName = _table.Rows[0]["TABLE_NAME"].ToString().Trim();

                    string sql = string.Format("SELECT * FROM [{0}]", strTableName);

                    _table = new System.Data.DataTable();

                    System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter(sql, oledbconn);

                    da.Fill(_table);

                }

                oledbconn.Close();

                //listview的Header需要对应Excel中的Header

                listExcel.ItemsSource=_table.DefaultView;

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢