首页 > 解决方案 > 如何打开多个excel文件并在DataGridView中打开它们

问题描述

我正在编写一个程序来过滤许多 Excel 文件并在 DataGridView 中显示结果。我从OpenFileDialog(我可以选择一个文件路径)开始显示我的过滤器有效,但现在我想选择许多文件并打开它们DataGridView然后过滤它们。

WFA (Visual Studio) 中是否有执行此操作的组件?我的意思是像 OpenFileDialog 但它打开/选择许多文件?我尝试使用此代码,但它显示了最后选择的文件,谢谢!

在这里输入代码

private void Button2_Click(object sender, EventArgs e)
    {

        try
        {

            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.Filter = "XML Files, Text Files, Excel Files| *.xlsx; *.xls; *.xml; *.txt; "; ;
            openFileDialog1.Multiselect = true;

            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                foreach (String file in openFileDialog1.FileNames)
                {
                    tb_path.Text = file;

                    // excelFilePath_com = tb_path.Text;

                    }


            }
            string constr = string.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source =" + tb_path.Text + ";Extended Properties = \"Excel 12.0; HDR=Yes;\"; ");

                    OleDbConnection con = new OleDbConnection(constr);
                    con.Open();
                    drop_down_sheet.DataSource = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    drop_down_sheet.DisplayMember = "TABLE_NAME";
                    drop_down_sheet.ValueMember = "TABLE_NAME";


            }


        catch (Exception ex)
        {
            MessageBox.Show(ex.Message,
         "Important Note",
         MessageBoxButtons.OK,
         MessageBoxIcon.Error,
         MessageBoxDefaultButton.Button1);
        }

    }

标签: c#

解决方案


OpenFileDialog 控件具有Multiselect允许您在同一个对话框中选择多个文件的属性。

openFileDialog1.Filter = "Excel files|*.xlsx|All files|*.*";
openFileDialog1.Multiselect = true;

然后稍后您可以使用该属性Filenames(而不是Filename)来检索您的文件:

foreach (string filePath in openFileDialog1.FileNames)   
{
    // ...
}

查看 MSDN了解更多信息。


推荐阅读