简体   繁体   中英

query to read a column excel worksheet with OLEDB

I'm totally new with OleDB and reading excel files. I have a worksheet with 3 columns (Name - Surname - E-mail Address) and I need to:

  • know the rows number
  • read all the addresses in the third columns
  • extract one by one each address

I use an OpenFileDialog object (ofd) and a TextBox (excel) to display the selected file. This is my code:

if (ofd.ShowDialog() == DialogResult.OK)
{
    excel.Text = ofd.FileName;
    connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excel.Text + ";Extended Properties=\"Excel 12.0 Xml;HDR=NO;IMEX=1\"";
    conn.ConnectionString = connection;
    conn.Open();
    string name_query = "SELECT A FROM[" + ofd.SafeFileName + "]";
    OleDbDataAdapter da = new OleDbDataAdapter(name_query, conn);
    da.Fill(table);
    conn.Close();
    j = table.Rows.Count;
}

It doesn't work, a query problem in the "FROM...". I usually read this type of query:

"SELECT * FROM [Sheet1$]"

but I can't find what Sheet1$ exactly is. Someone could explain me the right query?

2) To access to each element of the table (it would contain only the third column) and save it in a string variable what I have to do?

Thanks a lot!

To get the sheetnames, you can use the default getschema functionality from the data providers (connection.getschema). Without column headers (HDR=NO), the columns are named F1,F2,etc., so you for the third field, you could query on F3. If you want to be completely sure, you can also use getschema to get the column names of the sheet/table found with the first getschema. Finally, to get the values in a string list, you can use a bit of Linq (see the stringlist in the example). Not sure if you meant in a single string value, but if that's the case, you can use a string.join on the linq select.

Combined code starting form connection opening:

conn.Open();
var tableschema = conn.GetSchema("Tables");
var firstsheet = tableschema.Rows[0]["TABLE_NAME"].ToString();
string name_query = "SELECT F3 FROM [" + firstsheet + "]";
OleDbDataAdapter da = new OleDbDataAdapter(name_query, conn);
da.Fill(table);
conn.Close();
j = table.Rows.Count;
var stringlist = table.Rows.Cast<DataRow>().Select(dr => dr[0].ToString()).ToList();

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