Thursday 7 March 2013

Upload Excel And Show To GridView In ASP.NET Using C#.

1. Make A Folder Named  "Excels" Which Stores Uploaded Excel Files.
2. Be Careful About Your Excel Format. Create Excel With These Column Names...
S_ID, S_Name, S_Age, S_Sex, S_Hobby

And Sheet Name Perhaps  "Sheet1" Or As You Named........


<asp:FileUpload ID="FileUpload1" runat="server" />
       
  <asp:Button ID="txtupload" runat="server" Width="100" Text="Upload" OnClick="txtupload_Click" />
  <asp:Label ID="lblmsg" runat="server" Text=""></asp:Label>

<asp:GridView ID="gridEX1" runat="server" BackColor="White" BorderColor="#3366CC"
            BorderStyle="None" BorderWidth="1px" CellPadding="4">
            <RowStyle BackColor="White" ForeColor="#003399" />
            <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
            <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
            <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
            <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
        </asp:GridView>


*********************************************

protected void btnShowGrid_Click(object sender, EventArgs e)
    {

        string XL_Con = "";
        if (FileUpload1.HasFile == true)
        {
            string FileName = FileUpload1.FileName;
            string Extension = Path.GetExtension(FileName);

            if (Extension == ".xls" || Extension == ".xlsx")
            {

                string FilePath = Server.MapPath("Excels/" + FileName);
                FileUpload1.SaveAs(FilePath);
                switch (Extension)
                {
                    case ".xls":
                        XL_Con = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath(FileName) + ";" + "Extended Properties='Excel 8.0; HRD={1}'";
                        break;
                    case ".xlsx":
                        XL_Con = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Server.MapPath(FileName) + ";" + "Extended Properties='Excel 8.0; HRD={1}'";
                        break;
                }

                DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
                DbDataAdapter da = factory.CreateDataAdapter();
                DbCommand selectCommand = factory.CreateCommand();
                selectCommand.CommandText = "SELECT S_ID, S_Name, S_Age, S_Sex, S_Hobby FROM [Sheet1$]";

                DbConnection connection = factory.CreateConnection();

                connection.ConnectionString = XL_Con;
                selectCommand.Connection = connection;
                da.SelectCommand = selectCommand;
                DataSet cities = new DataSet();
                da.Fill(cities);

                gridEX1.DataSource = cities.Tables[0];
                gridEX1.DataBind();
            }
        }
    }



Enjoy Coding!!!

:)

No comments:

Post a Comment