C# .NET - Import Excel Sheet Data To DataGridView

Asked By Rahul on 17-Dec-10 01:44 AM
        
    hi all,
 i am new to .Net. here i hav error like couldnt find the path. pl help



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImportFromExcel.aspx.cs" Inherits="ImportFromExcel"%>

<!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 id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <table style="position: relative; left: 200px; top: 98px;">
        <tr>
          <td colspan="3">
            <asp:Label ID="lblError" runat="server" Visible="False" ForeColor="Red" Width="231px" style="position: static"></asp:Label></td>
        </tr>
        <tr>
          <td colspan="2">
            Select Your Excel File</td>
          <td style="width: 100px">
            <asp:FileUpload ID="FileUpload1" runat="server" /></td>
        </tr>
        <tr align="center">
          <td colspan="3">
            <asp:Button ID="btnImport" runat="server" Text="Import" OnClick="btnImport_Click" />
            <asp:Button ID="btnCancel" runat="server" Text="Cancel" /></td>
        </tr>
        <tr>
          <td colspan="3">
            <asp:Label ID="lblMessage" runat="server" Text="" ForeColor="green"></asp:Label>
            <asp:GridView ID="MyGrid" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
              Style="left: 23px; position: relative; top: 13px" Width="204px" AllowPaging="True" OnPageIndexChanging="MyGrid_PageIndexChanging" PageSize="5">
              <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
              <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
              <EditRowStyle BackColor="#999999" />
              <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
              <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
              <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
              <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            </asp:GridView>
          </td>
        </tr>
      </table>        
    </div>
    </form>
</body>
</html>

-----------------------------------------------------------------
codebehind.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.OleDb;


public partial class ImportFromExcel : System.Web.UI.Page
{
    public SqlConnection sqlcon = new SqlConnection("Data Source = MINDS3; User ID = sa; Password = minds; Initial Catalog=simple");
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Page.IsPostBack)
      {
        lblError.Visible = false;
      }

    }
    protected void btnImport_Click(object sender, EventArgs e)
    {
      string ExcelFilename = FileUpload1.PostedFile.FileName;
      string ExcelFileNameonly = ExcelFilename.Substring(ExcelFilename.LastIndexOf("\\") + 1);
      string FileExt = ExcelFilename.Substring(ExcelFilename.LastIndexOf(".") + 1);
      string Filenamewithoutextn = ExcelFileNameonly.Remove(ExcelFileNameonly.LastIndexOf("."));
      if (FileExt.ToLower() == "xls")
      {
        try
        {
          FileUpload1.PostedFile.SaveAs(Server.MapPath("/Imported Files/") + Filenamewithoutextn + ".xls");
          string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("/Imported Files/") + Filenamewithoutextn + ".xls;Extended Properties=Excel 8.0;";

          OleDbConnection olecon = new OleDbConnection(strConnectionString);

          int RecordCount = 0;
          lblMessage.Visible = false;
          lblError.Visible = false;
          olecon.Open();
          OleDbCommand cmd = olecon.CreateCommand();
          cmd.CommandText = "SELECT * FROM [Import$]";
          DataSet ds = new DataSet();
          OleDbDataAdapter da = new OleDbDataAdapter(cmd);
          OleDbDataReader dr = cmd.ExecuteReader();

          sqlcon.Open();
          string deletestr = "delete from importdata";
          SqlCommand sqlcmd = new SqlCommand(deletestr, sqlcon);
          sqlcmd.ExecuteNonQuery();

          while (dr.Read())
          {
            SqlCommand cmd1 = sqlcon.CreateCommand();
            cmd1.CommandText = "INSERT INTO ImportData values ('" + dr[0] + "','" + dr[1] + "')";
            cmd1.ExecuteNonQuery();
            RecordCount++;
            lblMessage.Visible = true;
            lblMessage.Text = " Processed Record # " + RecordCount.ToString();
          }
          dr.Close();
          olecon.Close();
          BindGrid();
          sqlcon.Close();
        }
        catch (Exception ex)
        {
          lblError.Visible = true;
          lblError.Text = ex.Message;
        }
      }

    }

    private void BindGrid()
    {
      try
      {
        lblError.Visible = false;
        SqlCommand cmd2 = sqlcon.CreateCommand();
        cmd2.CommandText = "SELECT * FROM ImportData order by UserID";

        DataSet sds = new DataSet();

        SqlDataAdapter sda = new SqlDataAdapter(cmd2);

        sda.Fill(sds, "ImportData");
        MyGrid.DataSource = sds.Tables["ImportData"].DefaultView;
        MyGrid.DataBind();
      }
      catch (Exception ex)
      {
        lblError.Visible = true;
        lblError.Text = ex.Message;
      }

    }
    protected void MyGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
      MyGrid.PageIndex = e.NewPageIndex;
      BindGrid();
    }
}
Gorav Handa replied to Rahul on 17-Dec-10 01:58 AM
The below statement is doing all these:
FileUpload1.PostedFile.SaveAs(Server.MapPath("/Imported Files/") + Filenamewithoutextn + ".xls");

As per this statement u r file should be at the location below:

Folder where u r web-page "ImportFromExcel" Resides  say 'ABC'
Folder u mentioned in above statement 'Imported Files'
Excel File - DataFile.xls

so u file location would be:
ABC\Imported Files\DataFile.xls

Now u r above statement will work.

Gorav Handa replied to Rahul on 17-Dec-10 02:04 AM
U might have missed to create "Imported Files" folder in u r application folder, as per my first comment in the folder "ABC".
Rahul replied to Gorav Handa on 17-Dec-10 02:34 AM
An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)..
 


 hi gourav,
\thanks ya, i done as u said,but still it shows another 1.  i am not using sql here
Gorav Handa replied to Rahul on 17-Dec-10 02:40 AM
As per u r code below u r using sql server DB named "MINDS3" and inserting data into table "ImportData" which resides in this DB.
Isn't it true?
Do u have SQL Server on u r machine?

public SqlConnection sqlcon = new SqlConnection("Data Source = MINDS3; User ID = sa; Password = minds; Initial Catalog=simple");
 sqlcon.Open();
          string deletestr = "delete from importdata";
          SqlCommand sqlcmd = new SqlCommand(deletestr, sqlcon);
          sqlcmd.ExecuteNonQuery();

          while (dr.Read())
          {
            SqlCommand cmd1 = sqlcon.CreateCommand();
            cmd1.CommandText = "INSERT INTO ImportData values ('" + dr[0] + "','" + dr[1] + "')";
            cmd1.ExecuteNonQuery();
            RecordCount++;
            lblMessage.Visible = true;
            lblMessage.Text = " Processed Record # " + RecordCount.ToString();
          }
          dr.Close();
          olecon.Close();
          BindGrid();
          sqlcon.Close();
Rahul replied to Gorav Handa on 17-Dec-10 03:20 AM
ya i hav sql 2005...

can i populate all the sheets in excel at a time to a data grid?

Gorav Handa replied to Rahul on 17-Dec-10 04:17 AM

You can do if the data is hierarchical. U can use master detail population of records within grid.