简体   繁体   English

使用C#在同一工作表中读取具有可变行长度的多个Excel表

[英]Reading Multiples excel tables having variable rows lenght in the same Worksheet using c#

So i have an excel file containing a worksheet with 4 tables My excel worsheet 所以我有一个包含4个表的工作表的Excel文件我的Excel工作表

i want to be able to get all of those tables to separate dataTable knowing that the lenght of the rows can change (rows can be added or deleted) 我想知道所有行的长度可以更改(可以添加或删除行),因此希望能够将所有这些表分隔为dataTable

I've tried using oleDb which work just fine with the first table in the worksheet but when i try to get the second one (by specifying the starting row) it give me the second table with all the others tables in one datatable :/ here is my code : 我试过使用oleDb,它可以与工作表中的第一个表很好地工作,但是当我尝试获取第二个表(通过指定起始行)时,它将第二个表与所有其他表一起放在一个datatable中://是我的代码:

 public static System.Data.DataTable getTableSelection(string file, string sheet, string starting = "", string finish = "")
    {
        string ConStr;
        string HDR;
        HDR = "YES";
        ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
            + file + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
        OleDbConnection cnn = new OleDbConnection(ConStr);
        string query = "select * from ["
                            + sheet + "$" + (starting != "" ? starting + ":" + finish : "") + "]";
        Console.WriteLine(query);
        OleDbCommand oconn = new OleDbCommand(query, cnn);
        OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
        System.Data.DataTable dt = new System.Data.DataTable();
        adp.Fill(dt);
        cnn.Close();
        return dt;
    }

Sorry for my bad english , hope you understand !! 对不起,我的英语不好,希望你能理解! love StackOverflow 爱StackOverflow

So i found a solution which consist on joining all my tables to get a all the fields i need and then transform it to a datatable by using oleDb query ; 因此,我找到了一种解决方案,该方案包括将所有表联接在一起以获得我需要的所有字段,然后使用oleDb查询将其转换为数据表; my query look like this : select * from (([Sheet1$A:D9] INNER JOIN [Sheet1$A14:D21] ON [Sheet1$A:D9].primaryKey=[Sheet1$A14:D21].primaryKey) INNER JOIN [Sheet2$A26:M33] ON [Sheet2$A26:M33].primaryKey=[Sheet1$A14:D21].primaryKey) 我的查询如下所示: select * from (([Sheet1$A:D9] INNER JOIN [Sheet1$A14:D21] ON [Sheet1$A:D9].primaryKey=[Sheet1$A14:D21].primaryKey) INNER JOIN [Sheet2$A26:M33] ON [Sheet2$A26:M33].primaryKey=[Sheet1$A14:D21].primaryKey)

but still , i am not being able to get the table without specifying where it should end :/ 但是仍然,我不能不指定应在何处结束获取表:/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM