简体   繁体   中英

Retrieving data from xlsx using OleDb(C#), how to get the count of lines in the xlsx?

My final goal is to retrieve the data from .xlsx file and load them into .mdb (Microsoft Access) file. My code is now like this:

    String fileName = "1.xlsx";
    OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"");
    conn.Open();
    DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
    string cmdText = "SELECT * FROM [sheet1$A3:B3]";
    DataSet ds;
    using (OleDbCommand cmd = new OleDbCommand(cmdText))
    {
        cmd.Connection = conn;
        OleDbDataAdapter adpt = new OleDbDataAdapter(cmd);
        ds = new DataSet();
        adpt.Fill(ds, "sheet1");
    }

But this is when I know how many lines are there in the sheet. What if I don't know about this information? Can I somehow manage to know how many lines are there in the sheet?

You don't need to assign columns and rows. You cold just do something like:

string cmdText = "SELECt * FROM [sheet1$]"

Or if you want to limit which columns to read:

string cmdText = "SELECt * FROM [sheet1$A1:B100000]"

Edit: Sorry, missed the part about needing to know how many rows there are. cilerler has your answer.

change the line

 string cmdText = "SELECT * FROM [sheet1$A3:B3]";

to

string cmdText = "SELECT * FROM [sheet1$]";

and add the following line to at the end of your code.

int numberOfRows = ds.Tables[0].Rows.Count;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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