How to import data from excel file to grid view ?

Here i will show that how can we import data from the excel file to gridview….

we will be using OLEDB instead of SQL because we will be using excel file as database & not sqlserver.

In HTML code just take the gridview & on button named Import.

I will look something like this….

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebImportExport.aspx.cs" Inherits="Forms_WebImportExport" %>  
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server"> 
<title>Untitled Page</title> 
</head> 
<body> 
<form id="form1" runat="server">
<div> 
<asp:Button ID="Import" runat="server"
OnClick="Import_Click" Text="Import" />
<br /> 
<asp:GridView ID="GridView1" runat="server"> 
</asp:GridView> 
<br /> 
</div> 
</form> 
</body> 
</html>

In Code behind…

using System.Data.OleDb; 
using System.IO;

public partial class Import_ExcelToGrid : System.Web.UI.Page
{     
  protected void Page_Load(object sender, EventArgs e)   
{             
}   

protected void Import_Click(object sender, EventArgs e)   
{ 
OleDbconnection con = new OleDbconnection
(@"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\\path\\vaibhav.xls;
Extended Properties=\"Excel 8.0;\");       
OleDbDataAdapter oleDA = new OleDbDataAdapter
("SELECT name , dept, salary from [sheet1$]", con);              
DataSet ds = new DataSet(); 
oleDA.Fill(ds);         
GridView1.DataSource = ds.Tables[0].DefaultView;     
GridView1.DataBind();   
}

Here i will pass my excel file in string which have to be imported to the gridview.

This will import he data from exel file to the gridview.

admin