using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
// Khob Aval az Hame Begam k In Code Faqat Baraye Anjam Yek File ast
protected void Button1_Click(object sender, EventArgs e)
{
// in Yek Connection String ast Ya Haman Address File EXCEL Shoma .
//k Shoma Faqat In Qesmat ROO D:\Persons.xls k Mahal Address File Ast Ro Taqir Bedid Baqie Ro Das NAzade BEzarid.
string connStringExcel = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Persons.xls;Extended Properties=""Excel 12.0;HDR=YES;""";
// Kamelan Moshakhse Code In 2 Khat Pain Ham k Etelaat File Ra Mikhannad
OleDbConnection excelConn = new OleDbConnection(connStringExcel);
OleDbCommand excelCmd = new OleDbCommand("Select * From [Sheet1$]", excelConn);
//
try
{
// az baqie jeshm poshi mikonam k hajm file nare bala
excelConn.Open();
OleDbDataReader excelReader = excelCmd.ExecuteReader();
//khob dar akhar Inke Connection String Barye Database khod Ra Ungone Ezaf Konid Vase inke Karemon 2ta nashe
string connStringSql = SqlDataSource1.ConnectionString;
// SqlDataSource1.ConnectionString in ebarat b in shey eshare mikone
//hala ingone code ra b databse khod vasl konid
//va hala ejra code va didan inke aya anjam mishavad
//
SqlConnection sqlConn = new SqlConnection(connStringSql);
try
{
//b dalil inke 3 dafe code roejra kardam intor shode na inke code 3 dafe varde karde bashe poshte sare ham
sqlConn.Open();
SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn);
// INJA Kheli MOheme Name Jadval Ra b Jaye "Persons" Qarar Dahid Maslan:
bulkCopy.DestinationTableName = "Persons";
bulkCopy.WriteToServer(excelReader);
Label1.Text = "Data successfully copied to SQL Server database table";
}
catch (Exception exs)
{
Label1.Text = exs.Message;
}
finally
{
sqlConn.Close();
}
}
catch (Exception exo)
{
Label1.Text = exo.Message;
}
finally
{
excelConn.Close();
}
}
}
درون این لینک فایل آموزشی و کد هست برای یاد گیری قدم به قدم دانلود کن با VS 2012 نوشتم