Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8774847
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T18:40:16+00:00 2026-06-13T18:40:16+00:00

I am importing excel sheet into sql server database the excelsheet contains 3 columns

  • 0

I am importing excel sheet into sql server database the excelsheet contains 3 columns id|data|passport I am using 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 : string a = ExcelRows[i1][“passport”].ToString();
ERROR: Object reference not set to an instance of an object.

also notice that when i run this after removing passport comparison the first row goes null in the database.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T18:40:17+00:00Added an answer on June 13, 2026 at 6:40 pm

    Look at this code:

        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()))
    

    You haven’t populated ExcelRows at all. You’ve created an array where every element is null. So of course ExcelRows[0]["passport"] will throw an exception.

    Why aren’t you using dt7.Rows to get the data?

    Additionally:

    • This code shouldn’t be in your presentation layer to start with
    • Avoid empty catch blocks
    • Try to refactor your code into smaller methods
    • Use a consistent naming style, ideally using camelCase for variable names
    • Give variables more meaningful names – what does dt7 really mean to you?
    • Use using statements for connections, commands etc
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am importing excel data into sql server using SqlbulkCopy, but the problem is
I am importing an Excel sheet into a SQL Server database. I am able
I am importing an excel sheet into my sql database. Everything works fine, but
I have some questions about importing data from Excel/CSV File into SQL Server. Let
I am importing excelsheet into sqlserver database but there are three columns in excel:
i am preparing myself for importing data from excel sheet to sql server 2005.I
i am currently working on importing data from excel sheet to sql server.i have
I'm importing data from an Excel sheet on to a DataTable using the following
My VB.NET application is using importing some excel sheet into access command.CommandText = SELECT
I am working on importing data from an Excel sheet to database. The Excel

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.