Friday, 30 May 2014

Add data from excel file to database

No comments
To show excel data in gridview

protected void btnShowExcelData_Click(object sender, EventArgs e)
    {
        string currpath = Server.MapPath("~/upload/payment.xlsx");
        string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + currpath + ";Extended Properties=Excel 12.0";

        OleDbConnection oledbConn = new OleDbConnection(connString);
        try
        {

            oledbConn.Open();


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

          
            OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
            // Pass the Select command to the adapter.
            objAdapter1.SelectCommand = cmd;
            // Create new DataSet to hold information from the worksheet.
            DataSet objDataset1 = new DataSet();
            // Fill the DataSet with the information from the worksheet.
            objAdapter1.Fill(objDataset1, "ExcelData");
            GridView1.DataSource = objDataset1;
            GridView1.DataBind();

        }
        catch (Exception ex)
        {
            lblInserted.Text = "" + ex;
        }
        finally
        {

            oledbConn.Close();
        }
    }


To insert data

protected void btnInsert_Click(object sender, EventArgs e)
    {
        GridView2.Visible = true;
        string currpath = Server.MapPath("~/upload/payment.xlsx");
        string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + currpath + ";Extended Properties=Excel 12.0";

        OleDbConnection oledbConn = new OleDbConnection(connString);


        oledbConn.Open();


        OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
        OleDbDataReader dr = cmd.ExecuteReader();


        while (dr.Read())
        {
          
            DataSet1TableAdapters.outstandingTableAdapter da1 = new DataSet1TableAdapters.outstandingTableAdapter();
            DataSet1.outstandingDataTable dt1 = new DataSet1.outstandingDataTable();
            DataSet1.outstandingRow dr0;
            dr0 = dt1.NewoutstandingRow();
            dr0.clientCode = dr[1].ToString();
            dr0.outstanding = dr[2].ToString().Trim();

            dr0.billValue = Convert.ToString(dr[3]);
            dr0.billcValue = dr[4].ToString();
            dr0.name = Convert.ToString(dr[5]);
            dr0.uname = Convert.ToString(dr[6]);
            dr0.EntryDateTime = Convert.ToDateTime(dr[7]);

            dt1.Rows.Add(dr0);
            lblInserted.Text = "Insetred";
            try
            {
               
                da1.Update(dt1);
            }
            catch (SqlException ex)
            {
                lblmsg.Text = "" + ex;
            }
        }