如何处理Datarow DBNull

时间:2015-08-03 09:54:51

标签: c#

以下代码为那些存储为文本"的代码返回空单元格。存储为文本的数字"我怎样才能获得这些细胞的价值?

string connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=yes;IMEX=2';");
foreach (var sheetName in GetExcelSheetNames(connectionString))
{
    using (OleDbConnection con1 = new OleDbConnection(connectionString))
    {
        var dt = new DataTable();
        string query = string.Format("SELECT  * FROM [{0}]", sheetName);
        con1.Open();
        OleDbDataAdapter adapter = new OleDbDataAdapter(query, con1);
        adapter.Fill(dt);
        for (int i = 1; i < dt.Rows.Count; i++)
        {
            for (int j = 1; j < dt.Columns.Count; j ++)
            {
                MessageBox.Show(dt.Rows[0][j].GetType().ToString());
            }
        }

enter image description here

2 个答案:

答案 0 :(得分:1)

var cell = dt.Rows[0][j] == System.DBNull.Value ? "null...", dt.Rows[0][j];

答案 1 :(得分:0)

对连接字符串中的混合类型使用IMEX = 1。