주 콘텐츠로 건너뛰기

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

  • 질문

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

    2019년 11월 28일 목요일 오후 2:13

답변

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

    • 답변으로 표시됨 sara87 2019년 12월 6일 금요일 오전 8:58
    2019년 11월 29일 금요일 오전 5:28