In this web programming tutorial we will learn that how we can import export excel data in to sql server database in asp.net using c#. In certain occasions we may need to export / import large excel spreadsheet to SQL server database.
Step 1:
I am assuming you have created a folder and uploaded your Microsoft Excel worksheet in that folder.
Step 2:
You can create class for creating an export function:
code for .cs file
Step 1:
I am assuming you have created a folder and uploaded your Microsoft Excel worksheet in that folder.
Step 2:
You can create class for creating an export function:
code for .cs file
using System; using System.Data; using System.Configuration; 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.Data.OleDb; /// /// Class for Exporting Excel Data to SQL server /// public class clsExcelToSqlServer { public clsExcelToSqlServer() { // // TODO: Add constructor logic here // } private string _FilePath; public String FilePath { get { return _FilePath; } set { _FilePath = value; } } public DataTable getDataFromExcelSheet() { try { //File path of Excel Spread sheet FilePath = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath) + "/ExcelFolder/ExcelAppliance.xls"; //Connection string to connect Excel data string strConnectionString = string.Empty; strConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath + @";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"""; OleDbConnection cnCSV = new OleDbConnection(strConnectionString); cnCSV.Open(); //Selecting all rows from excel sheet OleDbCommand cmdSelect = new OleDbCommand(@"SELECT * FROM [Sheet1$]", cnCSV); OleDbDataAdapter daCSV = new OleDbDataAdapter(); daCSV.SelectCommand = cmdSelect; DataTable dtCSV = new DataTable(); //Filling excel data into data table daCSV.Fill(dtCSV); cnCSV.Close(); daCSV = null; return dtCSV; } catch (Exception ex) { return null; } finally { } } }getDataFromExcelSheet() function returns a Data Table and you can use this Data table to export data into to SQL Server.
No comments:
Post a Comment