Why is OleDB ignoring Excel cells?

2019-05-21 13:09发布

问题:

Here's the setup:

I have an excel spreadsheet that has a very simple page. It looks like so:

I use the following connection string to access this file:

string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=NO\";", fn)

My function to access the file looks like:

try
{
    string select = string.Format("SELECT * FROM [{0}$]", tab.PageName);
    OleDbDataAdapter adapter = new OleDbDataAdapter(select, con);
    DataSet ds = new DataSet();

    adapter.Fill(ds, tab.PageName);


    // DEBUG: Let's just see what it is getting...
    for (int x = 0; x < 13; x++)
    {
        for (int y = 0; y < 3; y++)
        {
            Console.Write(ds.Tables[0].Rows[x][y].ToString() + "\t");
        }
        Console.WriteLine("");
    }
} 
catch
{ ... }

QUESTION

Why would the code NOT read some cells? Note that there is the text "Profit" at C5. I can read B5 just fine as "Revenue". I can read C6 just fine as an integer value. But Profit seems to vanish.

This isn't such a big problem with the header information, but entire blocks of real data refuse to be read. Instead it returns DBNull, even when the cell contains real, valid, usable data. The cells are all formatted exactly the same between cells that can read and cells that return DBNull.

I'm truly stumped!!!

Any thoughts?

回答1:

 new OleDbConnection("...TypeGuessRows=0;ImportMixedTypes=Text");

I have a hunch you may be experiencing a problem that I had previously.

Try adding those parameters to your connection string.



回答2:

I was having trouble getting the other answer+comment to work. The only setting needed was the IMEX=1 but it must be nested in single quotes in the Extended Properties, so here's an example of exactly how to format the additional IMEX setting:

connection.ConnectionString = 
  @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\somepath\somefile.xls;Extended Properties='Excel 8.0;IMEX=1';";


标签: c# excel oledb