显示报错后,点确定,程序还继续执行,怎么把报错去掉

解决方案 »

  1.   

    没有内容的单元格,如果你使用 ADO.NET 来读取 Excel,返回的当然就是 DBNull。你从原始的 Excel 就能看到哪些单元格可能没填写内容。
      

  2.   

    数据没对应上。
    参考:https://blog.csdn.net/C_gyl/article/details/85067599
      

  3.   

    加个判断呗
    if(dgvcells.value.equals(dbnull.value))
     {....}    
      

  4.   

    给你发一个我现在用的 ,增加引用Microsoft.Office.Interop.Excel.dll
           using System.Data.OleDb;
           using System.Collections;
           using Excel = Microsoft.Office.Interop.Excel;
             /// <summary>
            /// 根据文件名称filaname,表名称获得数据sheetname
            /// </summary>
            /// <param name="filename"></param>
            /// <param name="sheetname"></param>
            /// <returns></returns>
            public DataSet GetData(string filename,string sheetname)
            {
                string connStr = "";
                //string fileType = System.IO.Path.GetExtension("d:/test.xls");
                string fileType = System.IO.Path.GetExtension(filename);
                if (string.IsNullOrEmpty(fileType)) return null;            if (fileType == ".xls")
                    connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filename + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
                else
                    connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filename + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
                string sql_F = "Select * FROM [{0}]";            OleDbConnection conn = null;
                OleDbDataAdapter da = null;
                //DataTable dtSheetName = null;            da = new OleDbDataAdapter();
                DataSet ds = new DataSet();
                try
                {
                    // 初始化连接,并打开  
                    conn = new OleDbConnection(connStr);
                    conn.Open();                // 获取数据源的表定义元数据                         
                    
                    da.SelectCommand = new OleDbCommand(string.Format(sql_F, sheetname), conn);
                    DataSet dsItem = new DataSet();
                    da.Fill(dsItem, sheetname);                ds.Tables.Add(dsItem.Tables[0].Copy());
                   
                }
                catch
                {
                }
                finally
                {
                    // 关闭连接  
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                        da.Dispose();
                        conn.Dispose();
                    }
                }
                dataGridView1.DataSource = ds.Tables[0];