开发者

read db as all text

开发者 https://www.devze.com 2023-01-13 16:17 出处:网络
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?

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)
开发者_如何学C        {
            MessageBox.Show("An OleDb Error Thrown!" + "\n" + ex_oledb2.Message);
            return null;
        }
    }


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号