将Excel表加载到c#WinForms中已初始化的DataGridView中

本文关键字:初始化 DataGridView c#WinForms Excel 加载 | 更新日期: 2023-09-27 17:57:42

我正在尝试将Excel表数据附加到DataGridView中(dgvInitial)。一开始我用初始化DGV

private void DataForm_Load(object sender, EventArgs e)
    {
        int column = 100;
        int rows = 1000;
        dgvInitial.AutoGenerateColumns = false;
        for (int i = 1; i <= column; i++)
        {
            dgvInitial.Columns.Add("Col_" + i, "Col_" + i);
            dgvInitial.Columns[i - 1].FillWeight = 1;
        }
        for (int j = 0; j < rows; j++)
            dgvInitial.Rows.Add();
        foreach (DataGridViewColumn col in dgvInitial.Columns)
        {
            col.SortMode = DataGridViewColumnSortMode.NotSortable;
        }
    }

loadToolStripMenuItem_Click事件中,我试图将excel表附加到dgv中(源代码来自另一个stackerflow任务,但问题非常不同)

System.Data.OleDb.OleDbConnection MyConnection;
        System.Data.DataSet DtSet;
        System.Data.OleDb.OleDbDataAdapter MyCommand;
        MyConnection = new System.Data.OleDb.OleDbConnection(@"provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:'Sample.xlsx';Extended Properties=Excel 8.0;");
        MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
        MyCommand.TableMappings.Add("Table", "Net-informations.com");
        DtSet = new System.Data.DataSet();
        MyCommand.Fill(DtSet);
        dgvInitial.DataSource = DtSet.Tables[0];
        MyConnection.Close();

但这只是减少了dgv中的行数,我看不到任何数据。当我在DataForm_Load事件中注释所有内容时,它工作正常。

请问,你知道如何解决这个问题吗?事先非常感谢。

将Excel表加载到c#WinForms中已初始化的DataGridView中

尝试此格式的连接字符串,

     string Connectionstr = "";      
      string filePath ="C:'Sample.xlsx";
      string fileExtension = Path.GetExtension(filePath).ToLower();
      if (fileExtension == ".xls")
      Connectionstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
      if (fileExtension == ".xlsx")
      Connectionstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1'";
        MyConnection = new System.Data.OleDb.OleDbConnection(Connectionstr);
        MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
       MyCommand.TableMappings.Add("Table", "Net-informations.com");
        DtSet = new System.Data.DataSet();
       MyCommand.Fill(DtSet);
       dgvInitial.Columns.Clear();
       dgvInitial.AutoGenerateColumns = true;
       dgvInitial.DataSource = DtSet.Tables[0];
        MyConnection.Close();