.Net OleDbDataReader InvalidCast错误

时间:2018-04-07 22:51:20

标签: asp.net c .net oledb

您好我有一张excel表。我试图从这个文件中读取数据。 Datareader获取某些字段(列)的正确值。但是来到类别栏我得到“InvalidCastException”。

我的代码如下

public static List<Post> PostList(string path)
    {
        List<Post> post_list = new List<Post>();
        try
        {
            OleDbConnection oledbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
            try
            {
                OleDbCommand cmd = new OleDbCommand(); 
                cmd.Connection = oledbConn;
                cmd.CommandText = "SELECT * FROM [liste$] ";
                Post postt = null;
                oledbConn.Open();

                OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                try
                {
                    while (dr.Read())
                    {
                        postt = new Post();
                         postt.Post_Baslik = dr.GetString(dr.GetOrdinal("post_baslik"));
                        postt.Post_cat2 = Convert.ToInt32(dr.GetString(dr.GetOrdinal("Post_cat2")));
                        postt.Post_Cat = Convert.ToInt32(dr.GetInt32(dr.GetOrdinal("post_cat_id")));
postt.Post_Meta_Title = dr.GetString(dr.GetOrdinal("post_meta_title"));
                        postt.Post_Meta_Desc = dr.GetString(dr.GetOrdinal("post_meta_desc"));

                        post_listesi.Add(postt);
                    }
                    dr.Close();
                }
                finally
                {
                    if (dr != null)
                    {
                        ((IDisposable)dr).Dispose();
                    }
                }
            }
            finally
            {
                if (oledbConn != null)
                {
                    ((IDisposable)oledbConn).Dispose();
                }
            }
        }
        catch (Exception exception)
        {
            throw exception;
        }
        List<Post> posts = post_list;
        return posts;
    }

你会问我为什么我用Convert.toInt32而不是GetInt32。我试过了。 为什么我会遇到问题。我检查了我的excel表。值格式紧张。

0 个答案:

没有答案