简体   繁体   中英

Unable to upload excel file records to SQL database using aspx

I have an Aspx code to upload excel file records to SQL database. I am getting an error as System.NullReferenceException: Object reference not set to an instance of an object

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using System.Data.OleDb;

public partial class CSV : System.Web.UI.Page
{
    SqlConnection conn = new SqlConnection("Data Source=INHRPSM1D7C;Initial Catalog=HRSS;Integrated Security=True");
    DataSet ds;
    DataTable Dt;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

    private void ImporttoDatatable()
    {
        try
        {
            if (FlUploadcsv.HasFile)
            {
                string FileName = FlUploadcsv.FileName;
                string path = string.Concat(Server.MapPath("~/Document/" + FlUploadcsv.FileName));
                FlUploadcsv.PostedFile.SaveAs(path);

                OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
                OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon);
                OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);
                ds = new DataSet();
                objAdapter1.Fill(ds);
                Dt = ds.Tables[0];
            }
        }
        catch (Exception ex)
        {

        }
    }

    private void CheckData()
    {
        try
        {
            for (int i = 0; i < Dt.Rows.Count; i++)
            {
                if (Dt.Rows[i][0].ToString() == "")
                {
                    int RowNo = i + 2;
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "InvalidArgs", "alert('Please enter Employee ID in row " + RowNo + "');", true);
                    return;
                }
            }

            for (int i = 0; i < Dt.Rows.Count; i++)
            {
                if (Dt.Rows[i][1].ToString() == "")
                {
                    int RowNo = i + 2;
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "InvalidArgs", "alert('Please enter Name in row " + RowNo + "');", true);
                    return;
                }
            }

            for (int i = 0; i < Dt.Rows.Count; i++)
            {
                if (Dt.Rows[i][2].ToString() == "")
                {
                    int RowNo = i + 2;
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "InvalidArgs", "alert('Please enter Designation in row " + RowNo + "');", true);
                    return;
                }
            }

            for (int i = 0; i < Dt.Rows.Count; i++)
            {
                string date = DateTime.Parse(Dt.Rows[i][3].ToString()).ToString("dd/MM/yyyy");

                if (!ValidateDate(date))
                {
                    int RowNo = i + 2;
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "InvalidArgs", "alert('Wrong Date format in row " + RowNo + "');", true);
                    return;
                }
            }

            for (int i = 0; i < Dt.Rows.Count; i++)
            {
                if (Dt.Rows[i][4].ToString() == "")
                {
                    int RowNo = i + 2;
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "InvalidArgs", "alert('Please Enter City in Row " + RowNo + "');", true);
                    return;
                }
            }
        }
        catch (Exception ex)
        {

        }
    }

    private bool ValidateDate(string date)
    {
        try
        {
            string[] dateParts = date.Split('/');
            DateTime testDate = new DateTime(Convert.ToInt32(dateParts[2]), Convert.ToInt32(dateParts[1]), Convert.ToInt32(dateParts[0]));
            return true;
        }
        catch
        {
            return false;
        }
    }



    private void InsertData()
    {
        for (int i = 0; i < Dt.Rows.Count; i++)
        {
            DataRow row = Dt.Rows[i];
            int columnCount = Dt.Columns.Count;
            string[] columns = new string[columnCount];

            for (int j = 0; j < columnCount; j++)
            {
                columns[j] = row[j].ToString();
            }

            conn.Open();
            string sql = "INSERT INTO EmpImport(EmployeeID,Name,Designation,DateOfBirth,City)";
            sql += "VALUES('" + columns[0] + "','" + columns[1] + "','" + columns[2] + "',Convert(varchar(10),'" + columns[3] + "',103),'" + columns[4] + "')";
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.ExecuteNonQuery();
            conn.Close();
        }
    }

    protected void btnIpload_Click(object sender, EventArgs e)
    {
        ImporttoDatatable();
        CheckData();
        InsertData();
        BindGrid();
    }
    private void BindGrid()
    {
        DataSet ds = new DataSet();
        conn.Open();
        string cmdstr = "Select * from EmpImport";
        SqlDataAdapter adp = new SqlDataAdapter(cmdstr, conn);
        adp.Fill(ds);
        gvEmployee.DataSource = ds;
        gvEmployee.DataBind();
        ds.Dispose();
        conn.Close();
    }
}

@Mohammed Siddiq PS please Find the code:

         OleDbConnection OleDbcon = new     OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
         **OleDbcon.Open();** //Place it here.

        OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon);

        OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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