How to map Excel to SQL Server (dynamic SQL)?

I have a page that allows you to upload an Excel file. The server will then select the records from Excel and load them into a grid like this:

                cnx = new OleDbConnection();
                cnx.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                    filename + ";Extended Properties=" + (char)34 + "Excel 8.0;HDR=Yes;" + (char)34;

                string sql = "Select * from [" + tbl + "]";
                OleDbDataAdapter da = new OleDbDataAdapter(sql, getConnection());
                DataSet dst = new DataSet();
                da.Fill(dst);
                cnx.Close();
                Grid2.DataSource = PivotTable(dst);
                Grid2.DataBind();

I have a screenshot of what this looks like. My intention is to let the user select the values in the drop down to map to the corresponding headers of the uploaded Excel file, so the system can import the Excel file into the database. This is where I'm stuck... Say I have a hashtable that gets populated with the table column name and the Excel headers, how can I use that to write the Excel records to the database with the right Excel columns going to the right db columns?
radgrid-col.png
bemara57Asked:
Who is Participating?
 
jose_juanConnect With a Mentor Commented:
Hi,

I suggest to you create a temp Table to cache the Excel data, then your application load data from SQL Server table (not from Excel directly).

To load Excel to your SQL Server table you have many ways ( DTS, bcp, ...) I suggest to you other good way (see code), this is valid if your SQL Server have filesystem access to Excel file.

Good luck!

NOTE: you method (insert data using C#) is not good. Not in transaction!

-- Query to create temp Table
CREATE TABLE myTempExcel (
   ...
   cols
   ...
)
 
-- Query to update data from Excel to myTempExcel
BEGIN TRANSACTION
	TRUNCATE TABLE myTempExcel
 
	INSERT INTO myTempExcel (
		...cols...
	)
	SELECT	...cols...
	FROM	OPENROWSET(
			'Microsoft.Jet.OLEDB.4.0',
			'Excel 8.0; Database=C:\excelData\data.xls',
			[mySheetData$]
		)
COMMIT TRANSACTION
 
-- To read data from table into your app
  It's trivial!!

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.