0
votes

I have a website where one of the functions is importing excel sheets to a SQL database. Right now I am loading the data into a data table and then assigning a variable to a column index. That is working just fine, but if the excel sheet is in a different format then it wont import to the database.

Does anyone know of another way to import a specific column(s) into a SQL database other than using the column index? I have also used the column name, but what if the column name changes?

1
You don't include any details on exactly how you're performing the loading, so it would be difficult to suggest how to do it differently....Tim Williams

1 Answers

0
votes

You can use like this.

var fileName = string.Format("{0}\\fileNameHere", Directory.GetCurrentDirectory());
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);

var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();

adapter.Fill(ds, "anyNameHere");

DataTable data = ds.Tables["anyNameHere"];

The references for this is

1) How to read data from excel file using c#

2) Reading Excel files from C#

I hope it helps.