Saturday, 3 August 2013

Add Data in Excel sheet from asp.net page

aspx Page
=======

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Insert-Excel.aspx.cs" Inherits="Insert_Excel" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:TextBox ID="TextBox1" runat="server" Width="488px"></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>


.cs Page
======
add namespace:
using System.Data.OleDb;
using System.IO;

 protected void Button1_Click(object sender, EventArgs e)
    {
        string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=/Read-Data-From-Excel/App_Data/SampleData.xls" + ";" + "Extended Properties=Excel 8.0;";
        OleDbConnection Objconnec = new OleDbConnection();
        OleDbCommand ObjCmdSelect1;
        int success = 0;
        Objconnec.ConnectionString =sConnectionString;

        Objconnec.Open();

       /// string  qry1 = "insert into [Sheet1$] ([MdDesk]) values(@MdDesk)";
       string qry1 = "update [Sheet1$] set [MdDesk]=@MdDesk";
        ////string qry1 = "delete from [Sheet1$] ";
         ObjCmdSelect1 =new OleDbCommand(qry1,Objconnec);         
        ObjCmdSelect1.Parameters.Add("@MdDesk", TextBox1.Text);
        ObjCmdSelect1.Connection = Objconnec;

       success= ObjCmdSelect1.ExecuteNonQuery();

        Objconnec.Close();

    }

No comments:

Post a Comment