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

  • Domanda

  • Hi!

    I need help please in C#, How I can display multi excel files in datagridview behind each other .

    It is really hard and I'm a new in C#.

    Thank you!

    giovedì 28 novembre 2019 14:13

Risposte

  • 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.

    • Contrassegnato come risposta sara87 venerdì 6 dicembre 2019 08:58
    venerdì 29 novembre 2019 05:28