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

时间:2012-11-01 07:38:41

标签: c# asp.net sql

我将excel表导入sql server数据库excelsheet包含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";
            }
        }

    }
}
}
  

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

另请注意,当我在删除护照比较后运行此操作时,第一行在数据库中为空。

1 个答案:

答案 0 :(得分:4)

看看这段代码:

    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语句进行连接,命令等