OleDbDataReader How to read number types?

假如想象 提交于 2019-12-11 07:33:38

问题


Trying to read data from *.XLS file. I am able to read all the cell strings but unable to read the numbers in the cells. I have tried using .ToString() method with no success. Getting back a database null.

Code:

public xlsConverter(string excelFilePath, int numColumns)
        {
            string cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties='Excel 8.0;HDR=No;'", excelFilePath);
            string queryStr = "SELECT * FROM [Sheet1$]";

            using (OleDbConnection connection = new OleDbConnection(cnnStr))
            {
                OleDbCommand command = new OleDbCommand(queryStr, connection);
                connection.Open();
                OleDbDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    for(int i = 0; i <= numColumns; i++)
                    {
                        cleanedString.AppendFormat("{0}{1}", (reader[i].ToString()), "|");
                    }
                    cleanedString.AppendLine();
                }

                reader.Close();
            }
        }

cleanedString.AppendFormat("Row[{0}], DataType[{1}], String[{2}], Column[{3}] |-|", counter, (reader[i]).GetType(), reader[i].ToString(), i);

Produces:

Row[98], DataType[System.DBNull], String[], Column[4] |-|

Column 4 contains mixed strings and numbers, eg: 1300, 2341, 5000, 4000 (DED), 1243

Tried using “GetInt, GetValue, Parse, ‘casting’, ToString() etc”, but null is null! Anyone want to lead me in the right direction?

Sample XLS file:

https://github.com/abflett/adamflett_ca

https://github.com/abflett/adamflett_ca/blob/master/sample.xls


回答1:


Took some digging but ended up being a simple fix.

The connection string was the issue.

string cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0'", excelFilePath);

ImportMixedTypes=Text;TypeGuessRows=0

^Was added!

Youtube video I found it at: https://www.youtube.com/watch?v=jhPp_Hz54BU

and already answerd here at stackoverflow: Help with a OleDB connection string for excel files



来源:https://stackoverflow.com/questions/36723035/oledbdatareader-how-to-read-number-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!