views:

16

answers:

1

Im reading a xlsx file as a db to do some work

i noticed that its reading some feilds in as int and date even though i just want it all to come in as text . is there anyway to override this feature?

Code below

(feel free to point out anything i could be doing better with my code as well)

  private DataSet ExceltoDT(OpenFileDialog dialog)
    {
        try
        {
            string connst = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dialog.FileName + ";Extended Properties=\"Excel 12.0 Xml;HDR=NO\";";
            string sheet = "Sheet1$";
            string strSQL = "SELECT * FROM [" + sheet + "]";
            //string Table = "081710";
            OleDbConnection xlsdb = new OleDbConnection(connst);
            xlsdb.Open();
            OleDbDataAdapter adp = new OleDbDataAdapter(strSQL, xlsdb);
            DataSet ds2 = new DataSet();
            adp.Fill(ds2);


            adp.Dispose();
            xlsdb.Close();
            xlsdb.Dispose();

            return ds2;
        }
        catch (StackOverflowException stack_ex2)
        {
            MessageBox.Show("(2007 Excel file) Stack Overflowed!" + "\n" + stack_ex2.Message);
            return null;

        }
        catch (OleDbException ex_oledb2)
        {
            MessageBox.Show("An OleDb Error Thrown!" + "\n" + ex_oledb2.Message);
            return null;
        }
    }
+1  A: 

Add a ' (apostrophe) in front of every cell value. That will tell Excel "Treat this as text even when it looks like a number/date/whatever".

Not what you want? Then don't use the DB connector because it's badly broken. You'll notice that when you have a column with cells that are mixed. In that case, the DB driver will look at the first 8 rows and set the type to the majority of types it finds and return NULL for anything in that column that doesn't fit. You can fix that by hacking your registry.

Instead use the OLE API to open the Workbook and then start from there, reading row by row, converting the data as you need (this long list of posts should contain about every possible way to access Excel from C# plus all the bugs and problems you can encounter).

Aaron Digulla
do you ahve a good example of the old api to read a xls or xlsx?
Crash893
You can find the Excel API here: http://msdn.microsoft.com/en-us/library/aa209782(office.10).aspx PS: It's OLE, not "old" :-)
Aaron Digulla