C# Code for Move the data by using C# code.Create a table in SQL server next open the Microsoft Visual Studio IDE Create the new c# Console application then right click on the solution go to manage nuget package search the spreadsheet excel sheet library and install that package.
n sql create same fields table as tbl_students in Database
Goto solution explorer->right click on
//program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using DocumentFormat.Openxml.Packaging
using DocumentFormat.Openxml.Spreadsheet;
using System.Data.Sqlclient
using System.Data;
using System.Configuration;
using System.IO.Packaging;
namespace ExceltoTable
{
class Program
{
static void Main(string[],args)
{
try
{
string path = @"C:\Users\sample.xlsx";
string constr = (@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source="+path+";Extended Properties = Excel 12.0;");
OleDbConnection oconn = new OleDbConnection(constr);
OleDbConnection conn = new OleDbConnection(constr);
oconn.Open();
OleDbCommand olcmd = new OleDbCommand("select * from sheet1$",conn);
OleDbDataAdapter oda = new OleDbDataAdapter(olcmd);
DataTable dt = new DataTable();
oda.Fill(dt);
oconn.Close();
SqlConnection sqlcon = new SqlConnection(@"Data Source=.....");
sqlcon.Open();
using(SqlBulkCopy bc = new SqlBulkCopy(sqlcon))
{
bc.DestinationTableName = "tblname";
foreach(var column in dt.Columns)
bc.ColumnMappings.Add(column.ToString(),column.ToString())
bc.WriteToServer(dt);
}
sqlconn.Close();
}
catch(Exception ex)
{
throw ex;
}
}
}
}
good
ReplyDelete