Wednesday, December 10, 2008

Excel to Sql-server table Complete code C# asp.net 2.0 / 3.5, SqlBulkCopy

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


<!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:FileUpLoad id="FileUpLoad1" runat="server" />


<asp:Button id="UploadBtn" Text="Upload File" OnClick="UploadBtn_Click" runat="server" Width="105px" />


&nbsp;&nbsp;&nbsp;
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload To Sql Table" />
<asp:Label ID="Label1" runat="server" Width="188px"></asp:Label></div>
</form>
</body>
</html>
code Behind
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.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Data.Common;



public partial class Default5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void UploadBtn_Click(object sender, EventArgs e)
{
if (FileUpLoad1.HasFile)
{

// FileUpLoad1.SaveAs(@"c:\\inetpub\\wwwroot\\sftest3\\App_Data\\" + FileUpLoad1.FileName);
string filepath=Server.MapPath("~/App_Data/" + FileUpLoad1.FileName);
FileUpLoad1.SaveAs(filepath);

Label1.Text = "File Uploaded: " + FileUpLoad1.FileName ;
}
else
{
Label1.Text = "No File Uploaded.";
}

}


void dataupload()
{
// Connection String to Excel Workbook
string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\inetpub\\wwwroot\\sftest3\\App_Data\\ProductionFile.xls;Extended Properties=""Excel 8.0;HDR=YES;""";

// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select * FROM [Upload1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=Local;Initial Catalog=dev;User ID=dev;Password=dev";

// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "LeadTemp";
bulkCopy.WriteToServer(dr);
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
dataupload();
}
}

2 comments:

Unknown said...

Error in upload to SQL table...

Error message:

System.Data.OleDb.OleDbException: 'Upload1$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long.

Rajeev said...

'Upload1$' this will be your excel tab name, see on excel below left hand side.