0

我正在将 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";
            }
        }

    }
}
}

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

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

4

1 回答 1

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。您已经创建了一个数组,其中每个元素都为空。所以当然 ExcelRows[0]["passport"]会抛出异常。

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

此外:

  • 此代码不应该在您的表示层中开始
  • 避免空的 catch 块
  • 尝试将代码重构为更小的方法
  • 使用一致的命名风格,最好camelCase用于变量名
  • 给变量起更有意义的名字——对你dt7来说真正意味着什么?
  • 对连接、命令等使用using语句
于 2012-11-01T07:42:01.400 回答