如何显示从excel到C#datagridview的特定列

时间:2017-02-01 08:04:45

标签: c# excel datagridview

我无法在数据网格视图中显示从excel到c#的特定列。我不知道显示特定列的语法是什么。我使用oledb来显示da数据。

这是我的代码:

    private void WorkOrderTab()
    {
        string filePath = Path.GetFullPath(WOmain);
        string extension = Path.GetExtension(filePath);
        string conStr, sheetName;
        conStr = string.Empty;
        //Get the name of the First Sheet.
        using (OleDbConnection kuneksyon = new OleDbConnection(Excel07ConString))
        {
            using (OleDbCommand utos = new OleDbCommand())
            { 
                using (OleDbDataAdapter oda = new OleDbDataAdapter())
                {
                utos.Connection = kuneksyon;
                kuneksyon.Open();
                DataTable dtExcelSchema = kuneksyon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                kuneksyon.Close();
                DataTable dt = new DataTable();
                utos.Connection = kuneksyon;
                utos.CommandText = "SELECT * From [" + sheetName + "]";
                kuneksyon.Open();
                oda.SelectCommand = utos;
                oda.Fill(dt);
                kuneksyon.Close();
                //Populate DataGridView.
                WorkLoadDisp.DataSource = dt;
                label1.Text = dt.Rows.Count.ToString();
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

在分配数据并绑定数据时,在前端创建绑定字段。带标题ln的行将自动与第一列绑定,fn自动绑定到第二列。在Autogeneratecolumns="false"中设置datagridview

       <asp:BoundField DataField="ln" HeaderText="LastName"/>
       <asp:BoundField DataField="fn" HeaderText="FirstName"/>