【问题标题】:How to import selected columns and rows of excel file to listView c#如何将选定的excel文件的列和行导入listView c#
【发布时间】:2018-09-01 19:54:24
【问题描述】:

我正在使用listView 导入excel 文件,因为我的所有表格都是listView

如何将excel文件的选定列和行导入listView?因为它只有在我在第一行或“A1”中创建一列时才有效,如果可能的话,我可以使用与他们的名字或 ID 匹配的 where 查询吗?谢谢你帮我一把!

这是我的示例 Excel 文件,它将导入我的 listView。

我的代码

string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtFileName.Text + ";Extended Properties=Excel 12.0;";
DataTable table = new DataTable();
string excelName = "Sheet1";
string strConnection = string.Format(connStr);
OleDbConnection conn = new OleDbConnection(strConnection);
conn.Open();
OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + excelName + "$]", strConnection);

table.TableName = "TableInfo";
oada.Fill(table);
conn.Close();

// Clear the ListView control
listView1.Items.Clear();

// Display items in the ListView control
for (int i = 0; i < table.Rows.Count; i++)
{
    DataRow drow = table.Rows[i];

    // Only row that have not been deleted
    if (drow.RowState != DataRowState.Deleted)
    {
        // Define the list items
        ListViewItem lvi = new ListViewItem(drow["1ST"].ToString());

        // Add the list items to the ListView
        listView1.Items.Add(lvi);
    }
}

【问题讨论】:

    标签: c# winforms listview


    【解决方案1】:

    您需要从第一行获取所有值,即 A1 -> [...]1 并创建以这些值命名的列。然后添加所有行。

    抓取第一行,可能是这样的:

    foreach (Column c in ExcelColumns)
    {
        listView.Columns.Add(c.Value);
    }
    

    !请注意,这不一定是正确的代码,只是说明性的。

    ...然后阅读您的代码

    for (int i = 1; i < table.Rows.Count; i++)
    

    而不是

    for (int i = 0; i < table.Rows.Count; i++)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多