5
Answers

Question About Gridview

Photo of hamid saeed

hamid saeed

13y
2.3k
1
 
Hi Dear Friends,
How import excel file to gridvie and then save to sql server?

Thanks,
Best Regards,

Answers (5)

0
Photo of Senthilkumar
NA 15.2k 2.4m 13y
Hi,

private void btnImportExcelToGrid_Click(object sender,
System.EventArgs e)
{
String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\\Book2.xls;" +
"Extended Properties=Excel 8.0;";

DataSet ds = new DataSet();
//You must use the $ after the object
//you reference in the spreadsheet
OleDbDataAdapter da = new OleDbDataAdapter
("SELECT * FROM [Sheet1$]", strConn); 

//da.TableMappings.Add("Table", "ExcelTest");

da.Fill(ds);
DataGrid2.DataSource = ds.Tables[0].DefaultView;
DataGrid2.DataBind();
}

http://wiki.asp.net/page.aspx/825/loading-excel-data-into-a-gridview/
http://www.dotneter.com/import-excel-file-into-datagridview 
http://dotnetguts.blogspot.in/2006/10/import-excel-to-datagrid-aspnet.html 


Accepted
1
Photo of Satyapriya Nayak
NA 53k 8m 13y
Hi Hamid,

Try this...


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Show_Excel_gridview_insert_to_db._Default" %>

<!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:Table ID="TableButtons" runat="server">
            <asp:TableRow ID="TableRow1" runat="server">
                <asp:TableCell ID="TableCell1" runat="server">
                    <asp:Button ID="ButtonUpload" runat="server"
                    Text="Upload Excel Files" OnClick="ButtonUpload_Click" />
                </asp:TableCell>
                <asp:TableCell ID="TableCell2" runat="server">
                    <asp:Button ID="ButtonView" runat="server"
                    Text="View Excel Data"  OnClick="ButtonView_Click" />
                </asp:TableCell>
               
            </asp:TableRow>
        </asp:Table>
        <asp:Panel ID="PanelUpload" runat="server" Visible="False">
            <asp:FileUpload ID="FileUploadExcel" runat="server" />
            <br />
            Please select an Excel file to import:<br />
            <asp:Button ID="ButtonUploadFile" runat="server"
                Text="Upload File" OnClick="ButtonUploadFile_Click" /><br />
            <asp:Label ID="LabelUpload" runat="server" Text=""></asp:Label>
        </asp:Panel>
        <asp:Panel ID="PanelView" runat="server" Visible="False">
            <asp:Label ID="LabelGrid" runat="server" Text=""></asp:Label>
            <asp:GridView ID="GridViewExcel" runat="server" BackColor="#DEBA84" BorderColor="#DEBA84"
                BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">
                <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
                <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
                <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
                <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
            </asp:GridView>
        </asp:Panel>
        <asp:Panel ID="PanelImport" runat="server" Visible="False">
            <asp:Label ID="LabelImport" runat="server" Text=""></asp:Label>
        </asp:Panel>
        <asp:Label ID="lblError" runat="server" Text=""></asp:Label>
    </div>
    <asp:Button ID="btn_insert" runat="server" onclick="btn_insert_Click"
        Text="Insert to Db" />
       
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    </form>
</body>
</html>




using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace Show_Excel_gridview_insert_to_db
{
    public partial class _Default : System.Web.UI.Page
    {
        string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlCommand com;

        protected void ButtonUploadFile_Click(object sender, EventArgs e)
        {
            if (FileUploadExcel.HasFile)
            {
                try
                {
                    FileUploadExcel.SaveAs(Server.MapPath("~/ExcelImport.xls"));
                    LabelUpload.Text = "Upload File Name: " +
                        FileUploadExcel.PostedFile.FileName + "<br>" +
                        "Type: " + FileUploadExcel.PostedFile.ContentType +
                        " File Size: " + FileUploadExcel.PostedFile.ContentLength +
                        " kb<br>";
                }
                catch (System.NullReferenceException ex)
                {
                    LabelUpload.Text = "Error: " + ex.Message;
                }
            }
            else
            {
                LabelUpload.Text = "Please select a file to upload.";
            }
        }
        protected OleDbCommand ExcelConnection()
        {

            string ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("ExcelImport.xls") + ";" + "Extended Properties=Excel 8.0;";
            OleDbConnection Con = new OleDbConnection(ConnStr);
            Con.Open();
            OleDbCommand com = new OleDbCommand("SELECT * FROM [sheet1$]", Con);
            return com;

        }
        protected void ButtonView_Click(object sender, System.EventArgs e)
        {
            PanelUpload.Visible = false;
            PanelView.Visible = true;
            PanelImport.Visible = false;

            OleDbDataAdapter oledbda = new OleDbDataAdapter();
            oledbda.SelectCommand = ExcelConnection();
            DataSet ds = new DataSet();
            oledbda.Fill(ds);
            GridViewExcel.DataSource = ds.Tables[0].DefaultView;
            GridViewExcel.DataBind();
        }
        protected void ButtonUpload_Click(object sender, System.EventArgs e)
        {
            PanelUpload.Visible = true;
            PanelView.Visible = false;
            PanelImport.Visible = false;
        }

        protected void btn_insert_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow g1 in GridViewExcel.Rows)
            {
                SqlConnection con = new SqlConnection(connStr);
                com = new SqlCommand("insert into student(sid,sname,smarks,saddress) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "')", con);
                con.Open();
                com.ExecuteNonQuery();
                con.Close();

            }
            Label1.Text = "Records inserted successfully";
        }
    }
}




Thanks
If this post helps you mark it as answer
0
Photo of hamid saeed
NA 10 13.2k 13y
Hi My Friends, Thanks for your help, Best Regards,
0
Photo of Senthilkumar
NA 15.2k 2.4m 13y
Hi,

You no need to save the grid view.
The data is stored in the data table and which binded with the gridview control.

You need to iterate the datatable and insert the record into sql server.

foreach (DataRow drow in ds.Tables[0].Rows)
        {
            string col1 = drow[0].ToString();
            string col2 = drow[1].ToString();
            string col3 = drow[2].ToString();
            string col4 = drow[3].ToString();
            string col5 = drow[4].ToString();

            string _sqlInsert = "INSERT INTO Table1(column1,column2,column3,column4,column5) VALUES('"+col1+"','"+col2+"','"+col3+"','"+col4+"','"+col5+"')";

        }
0
Photo of hamid saeed
NA 10 13.2k 13y
Hi Dear, how save gridview data to sql? Thanks,