In this article I’m going to explain how to import records from excel sheet to SQL Server using ASP.NET and C#. If you want to import records from Excel sheet with validation please refer this article

Import records from excel sheet to SQL Server with validations in ASP.NET using C# 

          I got a requirement that I should import records from excel sheet to SQL Server.

To achieve that I have created demo and you could follow the steps given below.

1. Create a table for import the records to database

2. Upload excel sheet to the server folder

3. Fetch records from that excel sheet

4. Insert records to the table

5. Display the records to GridView

          So first we have to create a table for import the records to database. Table design could be like this.

Column Name

DataType

empid

varchar(50)

name

varchar(100)

designation

varchar(100)

city

varchar(50)

country

varchar(50)

 

Create Table script:

CREATE TABLE [dbo].[EmployeeDetails](

          [empid] [varchar](50) NULL,

          [name] [varchar](100) NULL,

          [designation] [varchar](100) NULL,

          [city] [varchar](50) NULL,

          [country] [varchar](50) NULL

) ON [PRIMARY]

Sample excel sheet:

          This is sample excel file which we are going to import records from this file.

 Excel import

          Here we have to create a folder. Then we could upload excel sheet to that folder which we have created.  

Sample code:

string FileName = FlUploadcsv.FileName;

string path = string.Concat(Server.MapPath("~/Document/" +

                                                                     FlUploadcsv.FileName));

 FlUploadcsv.PostedFile.SaveAs(path);

 

          Then we have to fetch records from excel sheet which is uploaded to the server folder.

Sample code:

OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");

 

                OleDbCommand command = new OleDbCommand("SELECT * FROM [Employee$]", OleDbcon);

                OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(command);

 

                OleDbcon.Open();

                // Create DbDataReader to Data Worksheet

                DbDataReader dr = command.ExecuteReader();

 

          After fetched the records from excel sheet we can insert the records to database by using  SqlBulkCopy class

Sample code:

  // SQL Server Connection String

  string constr = @"Data Source=SPIDER;Initial Catalog=Demo;Integrated Security=True";

 

                // Bulk Copy to SQL Server

                SqlBulkCopy bulkInsert = new SqlBulkCopy(constr);

                bulkInsert.DestinationTableName = "EmployeeDetails";

                bulkInsert.WriteToServer(dr);

 

Designer source code:

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

 

<!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></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

  <asp:FileUpload ID="FlUploadcsv" runat="server" />

                    <asp:Button ID="btnIpload" runat="server" Text="Import" OnClick="btnIpload_Click" />

<br />

<asp:GridView ID="gvEmployee" runat="server" width="100%">                        <HeaderStyle BackColor="#89A0FE" />

</asp:GridView>

</div>

    </form>

</body>

</html>

 

Here we have to use following namespaces

 

using System.IO;

using System.Data.OleDb;

using System.Data.Common;

 

Code behind:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.IO;

using System.Data.SqlClient;

using System.Data.OleDb;

using System.Data.Common;

public partial class CSV : System.Web.UI.Page

     SqlConnection conn = new SqlConnection("Data Source=SPIDER;Initial Catalog=Demo;Integrated Security=True");

 

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            BindGrid();

        }

    }

 

    void ImporttoDatatable()

    {

        try

        {

            if (FlUploadcsv.HasFile)

            {

                string FileName = FlUploadcsv.FileName;

                string path = string.Concat(Server.MapPath("~/Document/" + FlUploadcsv.FileName)); 

                FlUploadcsv.PostedFile.SaveAs(path); 

                OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;"); 

                OleDbCommand command = new OleDbCommand("SELECT * FROM [Employee$]", OleDbcon);

                OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(command); 

                OleDbcon.Open();

                // Create DbDataReader to Data Worksheet

                DbDataReader dr = command.ExecuteReader(); 

                // SQL Server Connection String

                string constr = @"Data Source=SPIDER;Initial Catalog=Demo;Integrated Security=True"; 

                // Bulk Copy to SQL Server

                SqlBulkCopy bulkInsert = new SqlBulkCopy(constr);

                bulkInsert.DestinationTableName = "EmployeeDetails";

                bulkInsert.WriteToServer(dr);

                OleDbcon.Close();

            }

        }

        catch (Exception ex)

        {          

        }   

    }

    void BindGrid()

    {

        DataSet ds = new DataSet();

        conn.Open();

        string cmdstr = "Select * from EmployeeDetails";

        SqlCommand cmd = new SqlCommand(cmdstr, conn);

        SqlDataAdapter adp = new SqlDataAdapter(cmd);

        adp.Fill(ds);

        gvEmployee.DataSource = ds;

        gvEmployee.DataBind();

        ds.Dispose();

        conn.Close();

    } 

    protected void btnIpload_Click(object sender, EventArgs e)

    {

        ImporttoDatatable();

        BindGrid();

    }

}

 

Note:

          While running this demo maybe you will get error something like

The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.

          So you could download and install 2007 Office System Driver: Data Connectivity Components. Download link is given below.

 

http://www.microsoft.com/en-us/download/confirmation.aspx?id=23734


cytotec abortion

an abortion pill buy abortion pills online
medical abortion pill online abortion pill abortion pill


View demo Download
http://www.dotnetfox.com/Document/1117/0photo8.jpg

If you enjoyed this article, get email updates (it's free).


Related Articles
  • How to add edit delete update records in Grid view ASP.NET Introduction: In this article i'm going to explain how to add delete edit records in Grid view. Description: If we want to add delete edit records in grid view we should use following grid view events, 1. onrowcommand 2. onrowdeleting 3. onrowupdating 4. onrowcancelingedit 5. onrowediting Also we should use following template field in Grid View. 1.ItemTemplate : ItemTemplate is used to display rec...
  • How to insert edit delete update records in Grid view using WCF In this article i'm going to explain how to insert records using WCF. Windows Communication Foundation (WCF) is an extension of the .NET framework to build and run connected systems. Windows Communication Foundation provides a unified framework for building secure and reliable transacted Web services. Windows Communication Foundation combines and extends the capabilities of Distributed System...
  • File Upload in Gridview ASP.NETIn this article I’m going to explain how to use file upload control in grid view for uploading images or files to the server. The FileUpload control allows you to provide users with a way to send a file from their computer to the server. The control is useful for allowing users to upload images, text files or other files. Here I’ll show you how to use file upload control in gridview to upload the ...
  • Check or Uncheck all check box in ASP.NET Gridview using JavaScriptIn this article I’m going to explain how to add CheckBox control in Gridview to Check or Uncheck all checkbox using JavaScript. To implement this concept we have to add one Checkbox control in Gridview header template and one more checkbox control in Gridview item template. here we need to use javascript to avoid postback and change gridview row color if checkbox was checked or unchecked.
  • Insert delete update records in XML file -ASP.NET using c# In this article I’m going to explain how to insert delete update records in XML file using ASP.NET and C#. XML was created to structure, store and transport data. What is XML? XML stands for EXtensible Markup Language XML is a markup language much like HTML XML was designed to carry data, not to display data XML tags are not predefined. You must define your own tags
  • How to use DropDownList control to GridView in ASP.NET using c# In this article I’m going to explain how to use DropDownList control in ASP.NET using C#. ASP.NET allows you to use any server controls in GridView. In this article I’ll show you how to use DropDownList control in GridView. DropDownList can be used to select only one item at a time item. It’s very easy to use DropDownList control in GridView. We need to use OnRowDataBound event to bind DropDownLis...
  • Export GridView data to excel using ASP.NET and c# In this article I’m going to explain how to export GridView data to excel using ASP.NET and C#. Sometimes we need to export gridview data to excel. Here I’ll show you how to export GridView data to Excel by using RkLib ExportData. RKLib ExportData is a class library used to export data to excel. So here we have to create table and fetch the records to DataTable and we can export to excel.
  • How to use Ajax CalenderExtender in ASP.NET GridViewIn this article I’m going to explain how to use Ajax CalenderExtender in ASP.NET GridView. Today one of my blog subscriber asked me a question that’s how to use Ajax CalenderExtender in ASP.NET GridView. I hope you already know how to use Ajax CalenderExtender in normal page. There is no different to use Ajax CalenderExtender in normal page and GridView.
  • Create dynamic GridView or programmatically create ASP.NET GridView with dynamic BoundField In this article I’m going to explain how to create dynamic GridView or programmatically create GridView with dynamic BoundField in ASP.NET using C#. In some scenario it is necessary to create dynamic GridView with BoundField instead of static one. Here I’ll explain how to create dynamic GridView which includes dynamic BoundFiled, apply custom styles to header row and data row. After creating dyna...
  • How to export GridView data to PDF document in ASP.NET with C# using iTextSharpIn this article I’m going to explain how to export GridView to PDF document. Other articles related to iTextSharp. iTextSharp is a C# port of iText, and open source Java library for PDF generation and manipulation. It can be used to create PDF documents from scratch, to convert XML to PDF (using the extra XFA Worker DLL), to fill out interactive PDF forms, to stamp new content on existing PDF doc...

Comments
comments powered by Disqus

Thanks for downloading..!!

×
Subscribe via Email
    
message to display in fancybox