繁体   English   中英

如何将Excel文件的选定列和行导入到ListView C#

[英]How to import selected columns and rows of excel file to listView c#

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

如何将Excel文件的选定列和行导入到listView 因为仅当我在第一行或“ A1”中创建一列时,它才起作用,并且如果可能的话,我可以在哪里使用与其名称或ID相匹配的查询? 谢谢您的帮助!

这是我的示例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);
    }
}

您需要从第一行(即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++)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM