0

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!

imsome1
  • 1,182
  • 4
  • 22
  • 37
Frank Lioty
  • 949
  • 3
  • 10
  • 17

1 Answers1

4

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();
imsome1
  • 1,182
  • 4
  • 22
  • 37
Me.Name
  • 12,259
  • 3
  • 31
  • 48
  • I added it, but he doesn't work (an error at "da.Fill(table)"). What's that "Tables" string? And "TABLE_NAME"? Firstsheet? In this way I can't understand a thing. – Frank Lioty Jun 15 '12 at 14:36
  • When using OLEDB on excel, the sheets are interpreted as tables. Thus, querying the tableschema for table names, returns the sheet names. tableschema.Rows[0] returns the datarow with information on the first table. ["TABLE_NAME"] calls the column index on the datarow with the name table_name, which contains the name of the sheet. – Me.Name Jun 15 '12 at 15:31