Click here to Skip to main content
15,900,589 members
Please Sign up or sign in to vote.
1.60/5 (3 votes)
See more:
I want to insert data from an Excel file into an SQL table, by matching the column names in the Excel file with the field names in the table. For instance, in my page (form?), I have a drop-down list containing a list of table names from the SQL DB, from which a user can select one as the destination. Into this table, I want to insert data from an Excel file, matching columns with field names. Please point me to some samples.
Thanks.
Posted
Updated 17-Oct-11 8:44am
v2
Comments
ChandraRam 17-Oct-11 14:45pm    
Google will give you loads of samples for this. What have you tried?

Here is how can do so.
C#
private void button1_Click(object sender, EventArgs e)
{
	try {
		DataTable sheetTable = loadSingleSheet("C:\\excelFile.xls", "Sheet1$");
		updateDataTable(sheetTable);
	} catch (Exception ex) {
		System.Response.Write(ex.Message);
	}
}

public void updateDataTable(DataTable dt)
{
	using (SqlConnection connection = new SqlConnection(connectionString)) {
		SqlDataAdapter adapter = new SqlDataAdapter();
		DataSet ds = new DataSet();
		ds.Tables.Add(dt);
		adapter.Update(ds);
	}
}

private OleDbConnection returnConnection(string fileName)
{
	return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
}

private DataTable loadSingleSheet(string fileName, string sheetName)
{
	DataTable sheetData = new DataTable();
	using (OleDbConnection conn = this.returnConnection(fileName)) {
		conn.Open();
		// retrieve the data using data adapter
		OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);
		sheetAdapter.Fill(sheetData);
	}
	return sheetData;
}


It might need some tuning but this is how you will do basically.
 
Share this answer
 
v3
SQL
BULK INSERT MyTable FROM 'D:\myexcel.csv'
WITH
(
	FIRSTROW=2,
	FIELDTERMINATOR=',',
	ROWTERMINATOR='\n' 
)


Your table must match exact column sequence as you have in Excel.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900