繁体   English   中英

你调用的对象是空的。 阅读Excel

[英]Object reference not set to an instance of an object. Reading Excel

我正在将Excel工作表导入到SQL Server数据库中,Excel工作表包含3列id | data | passport我正在使用SqlBulkCopy

{
    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString);

string[] filePaths = null;
string strFileType = null;
string strFileName = null;
string strNewPath = null;
int fileSize;
int flag=0;

protected void Page_Load(object sender, EventArgs e)
{

}



protected void Button1_Click1(object sender, EventArgs e)
{
    strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
    strFileName = FileUpload1.PostedFile.FileName.ToString();
    FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
    strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
    fileSize = FileUpload1.PostedFile.ContentLength / 1024;

    //EXCEL DETAILS TABLE
    con.Open();
    //=========================================
    DataTable dt8 = new DataTable();
    SqlCommand cmd8 = new SqlCommand("insert into exceldetails (name,type,details,size)" + "values(@name,@type,@details,@size)", con);
    cmd8.Parameters.Add("@name", SqlDbType.VarChar).Value = strFileName;
    cmd8.Parameters.Add("@type", SqlDbType.VarChar).Value = strFileType;
    cmd8.Parameters.Add("@details", SqlDbType.VarChar).Value = DateTime.Now;
    cmd8.Parameters.Add("@size", SqlDbType.Int).Value = fileSize;
    cmd8.ExecuteNonQuery();
    con.Close();
    try
    {
        SqlDataAdapter da8 = new SqlDataAdapter(cmd8);
        da8.Fill(dt8);
    }
    catch { }
    //=========================================

    //CHOOSING EXCEL CONNECTIONSTRING

    string excelConnectionString = "";
    switch (strFileType)
    {
        case ".xls":

            excelConnectionString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strNewPath + "; Extended Properties=Excel 8.0;");
            break;
        case ".xlsx":
            {
                excelConnectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strNewPath + "; Extended Properties=Excel 12.0 Xml;");

                break;
            }
    }

    //===================================
    //PRE EXCEL COUNT

    // Create Connection to Excel Workbook
    using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
    {
        connection.Open();
        OleDbCommand command = new OleDbCommand("Select ID,Data,passport FROM [Sheet1$]", connection);
        OleDbCommand command1 = new OleDbCommand("select count(*) from [Sheet1$]", connection);

        //Sql Server Table DataTable
        DataTable dt4 = new DataTable();
        SqlCommand cmd4 = new SqlCommand("select * from excelsheet", con);
        try
        {
            SqlDataAdapter da4 = new SqlDataAdapter(cmd4);
            da4.Fill(dt4);//sql table datatable
        }
        catch { }

        //===============================

        //excelsheet datatable
        DataTable oltlb = new DataTable();
        OleDbCommand olcmd = new OleDbCommand("select * from [Sheet1$]", connection);
        try
        {
            OleDbDataAdapter olda = new OleDbDataAdapter(olcmd);
            olda.Fill(oltlb); //excel table datatable
        }
        catch { }

        //==============================


        using (DbDataReader dr = command.ExecuteReader())
        {
            // SQL Server Connection String
            string sqlConnectionString = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";

            con.Open();
            DataTable dt7 = new DataTable();
            dt7.Load(dr);
            DataRow[] ExcelRows = new DataRow[dt7.Rows.Count];
            DataColumn[] ExcelColumn = new DataColumn[dt7.Columns.Count];

            //=================================================
            for (int i1 = 0; i1 < ExcelRows.Length; i1++)
            {

                if(string.IsNullOrEmpty(ExcelRows[i1]["passport"].ToString()))
                {
                    ExcelRows[i1]["passport"]="0";

                }

                string a = Convert.ToString(ExcelRows[i1]["passport"]);
                char a1 = a[0];

                if (a1 >= 'A' || a1 <= 'Z')
                {
                    Label12.Text = "CAPITAL";
                    break;
                }
                else
                {
                    Label12.Text = "notgood";


                    flag = flag + 1;

                }

            }
            //=========================================================

            if (flag == 0)
            {
                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
                {
                    bulkCopy.DestinationTableName = "ExcelTable";
                    dt7.Rows.CopyTo(ExcelRows, 0);

                    //==========================================================================================
                    for (int i = 0; i < ExcelRows.Length; i++)
                    {
                        if (ExcelRows[i]["passport"] == DBNull.Value)
                        {
                            ExcelRows[i]["passport"] = 0;
                        }

                    }
                    bulkCopy.WriteToServer(ExcelRows);
                    //==========================================================================================
                    for (int i = 0; i < ExcelRows.Length; i++)
                    {
                        if (ExcelRows[i]["data"] == DBNull.Value)
                        {
                            // Include any actions to perform if there is no date
                            //ExcelRows[i]["data"] = Convert.ToDateTime("0");
                        }
                        else
                        {
                            DateTime oldDate = Convert.ToDateTime(ExcelRows[i]["data"]).Date;
                            DateTime newDate = Convert.ToDateTime(oldDate).Date;
                            ExcelRows[i]["data"] = newDate.ToString("yyyy/MM/dd");
                        }

                    }

                    //==========================================================================================
                }
                //======

            }
            else
            {
                Label13.Text = "Wrong Format";
            }
        }

    }
}
}

错误:字符串a = ExcelRows [i1] [“ passport”]。ToString(); 错误:对象引用未设置为对象的实例。

还应注意,当我在删除护照比较后运行此文件时,第一行在数据库中为空。

看这段代码:

    DataRow[] ExcelRows = new DataRow[dt7.Rows.Count];
    DataColumn[] ExcelColumn = new DataColumn[dt7.Columns.Count];

    for (int i1 = 0; i1 < ExcelRows.Length; i1++)
    {
        if(string.IsNullOrEmpty(ExcelRows[i1]["passport"].ToString()))

您根本没有填充 ExcelRows 您已经创建了一个数组,其中每个元素都为null。 因此, 当然 ExcelRows[0]["passport"]将引发异常。

为什么不使用dt7.Rows获取数据?

另外:

  • 此代码不应该在您的表示层中开头
  • 避免空的捕获块
  • 尝试将代码重构为较小的方法
  • 使用一致的命名样式,最好使用camelCase作为变量名
  • 给变量赋予更有意义的名称dt7对您真正意味着什么?
  • 使用using语句进行连接,命令等

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM