Yogesh Vedpathak

Yogesh Vedpathak

  • 615
  • 1.4k
  • 191.5k

I want to Insert Form data to excel sheet

Jan 27 2017 9:23 AM
I Am Trying to Insert Form Data To Excel sheet But GettingError  Please have look in a code and guide me in that way  
 
 
 
 
int result = cmd.ExecuteNonQuery(); // getting error here let me know why this happpens  
 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
namespace Test
{
public partial class FormToExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BtnLogin_Click(object sender, EventArgs e)
{
string ConStr = "ExcelInsertDataExcel.xlsx";
string path = Server.MapPath("InsertDataExcel.xlsx");
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +Server.MapPath("Excel/InsertDataExcel.xlsx") + ";Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=Yes;\"";
string query = "INSERT INTO [Sheet1$] ([FirstName],[LastName],[Address],[City],[State],[Zip],[IsActive] ) VALUES('" + txtFirstName.Text + "','" + txtLastName.Text + "','" + txtAddress.Text + "','" + txtCity.Text + "','" + DropDownList1.SelectedValue + "','" + txtZip.Text + "','" + CheckBoxList1.SelectedValue + "')";
OleDbConnection conn = new OleDbConnection(ConStr);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("@LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
cmd.Parameters.AddWithValue("@City", txtCity.Text);
cmd.Parameters.AddWithValue("@State", DropDownList1.SelectedItem.Text);
cmd.Parameters.AddWithValue("@Zip", txtZip.Text);
cmd.Parameters.AddWithValue("@IsActive", CheckBoxList1.SelectedItem.Text);
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
Response.Write("<script>alert('Sucessfully Data Inserted Into Excel')</script>");
}
else
{
Response.Write("<script>alert('Sorry!\n Insertion Failed')</script>");
}
conn.Close();
}
}
}

Answers (3)