使用openFileDialog将excel文件导入datagridview

时间:2015-06-12 15:08:54

标签: c# excel winforms datagridview

我有一个带有加载按钮的winform。单击加载时,我选择要加载到datagridview中的文件。当我单击该文件时,似乎填充了正确的行数,但没有显示任何内容。我不确定我错过了什么。 "缩略语"是我的Excel选项卡/表格的名称。

   private void btnImport_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "XLS files (*.xls, *.xlt)|*.xls;*.xlt|XLSX files (*.xlsx, *.xlsm, *.xltx, *.xltm)|*.xlsx;*.xlsm;*.xltx;*.xltm|ODS files (*.ods, *.ots)|*.ods;*.ots|CSV files (*.csv, *.tsv)|*.csv;*.tsv|HTML files (*.html, *.htm)|*.html;*.htm";
            openFileDialog.FilterIndex = 2;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                System.Data.OleDb.OleDbConnection MyConnection;
                System.Data.DataSet DtSet;
                System.Data.OleDb.OleDbDataAdapter MyCommand;
                MyConnection = new System.Data.OleDb.OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + openFileDialog.FileName + "';Extended Properties=Excel 8.0;");
                MyConnection.Open();
                MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Acronyms$]", MyConnection);
                DtSet = new System.Data.DataSet();
                MyCommand.Fill(DtSet);
                dgvExcelList.DataSource = DtSet.Tables[0];
                MyConnection.Close();
            }
        }

1 个答案:

答案 0 :(得分:0)

检查以确保通过GUI为DataGridView创建的列填充了DataProperty值。