none
How to open multi excel files in datagridview at the same time in C# RRS feed

Réponses

  • Hi sara87,
    You can use the method Directory.GetFiles() to get the files, then use OleDbDataAdapter Class to get the data.
    Here is my code example and you can refer to it.

    public Form1()
    {
        InitializeComponent();
        GetFilesList();
    }
    
    public void GetFilesList()
    {
        var ListFiles = Directory.GetFiles(@"C:\Users\danielzh\Desktop", "*.xlsx", SearchOption.AllDirectories);
        foreach (string FilePath in ListFiles)
        {
            ImportExcel(FilePath);
        }
    }
    DataTable dt = new DataTable();
    public void ImportExcel(string FilePath)
    {
        string ConnStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\";";
        OleDbConnection Conn = new OleDbConnection(ConnStr);
        OleDbDataAdapter DA = new OleDbDataAdapter("select * from [Sheet1$]", ConnStr);
        DA.Fill(dt);
        dataGridView1.DataSource=dt;
        Conn.Close();
    }

    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marqué comme réponse sara87 vendredi 6 décembre 2019 08:58
    vendredi 29 novembre 2019 05:28