WPF 读取Excel数据到listview中显示

 时间:2026-02-15 08:05:43

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;

  • 如何组织和管理好一帮程序员?
  • 如何正确使用tar命令
  • jq输出当前日期时间,个位补零0拼接时间
  • 爱站首页反链查询工具使用方法
  • 如何清除input表单的记忆
  • 热门搜索
    我是什么课文 macd是什么意思 为什么人死了要说rip 焱是什么意思 梦见棺材是什么征兆 释义是什么意思 husband是什么意思 毒龙钻是什么意思 85年属什么生肖 suv什么意思