Below is a sample code in migrating or importing as CSV file to SQL database:
void Migrate_CSV_File_To_Database()
{
if (FileUpload1.HasFile)
{
const string saveFolder = @"C:\temp\imported";
string filePath = Path.Combine(saveFolder, FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
string connString = WebConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
var excelConnString =
String.Format(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;IMEX=1\"",
filePath);
//Create Connection to Excel work book
using (var excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
const string strSelect = "SELECT [Column1], [Column2], [Column3], [Column4] FROM [Sheet1$]";
using (var cmd = new OleDbCommand(strSelect, excelConnection))
{
excelConnection.Open();
using (var dReader = cmd.ExecuteReader())
{
using (var sqlBulk = new SqlBulkCopy(connString))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Destination_Table_Name";
sqlBulk.WriteToServer(dReader);
}
}
excelConnection.Close();
}
}
}
}
No comments:
Post a Comment