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;
سؤال
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?
المحلول
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;
نصائح أخرى
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.