Question

I wrote a code using c#- Visual 2008- that takes:

1- an excel sheet.

2- Opens a connection to Excel

3- Reads the Column names using the OleDbDataReader object and GetTableSchema method

4- Added the Columns names in an array

5- Created a Table that has the same Column names as the EXcel sheet ( i used CREATE table
command)

6-Then once i have the table created in SQL , i loop over the excel rows an add the data into sql using Insert command.

Now My problem is:

In the " create table" command , i have to specify the DATATYPE for the column !i.e.

CREATE TABLE "table_name"
("column 1" "data_type_for_column_1",
"column 2" "data_type_for_column_2",
... )

HOW should i solve this problem? Are the datatypes that excel columns can be, the same as the datatypes in SQL server? is there some kind of mapping ? please help me out. thank you

Was it helpful?

Solution

OleDbDataReader.GetSchemaTable will give you what the underlying datatype is from the spreadsheet. This (quote):

Maps to the .NET Framework type of the column.

You then need to map that to the appropriate SqlDbType. Check out this other answer for ideas on how to do that.

The other point I wanted to raise as a side point, was to consider bulk loading the data from excel into SQL Server instead of "read a row / insert a row". I don't know what data volumes you're talking about, but that could speed the process up.

OTHER TIPS

I believe you can use. sql_variant data type if you dont know what kind it is going to be? i'd take a look at that.

http://msdn.microsoft.com/en-us/library/ms173829.aspx

You can figure out the data type of the column using GetTableSchema()...

              DataTable  schema  =  rdr.GetSchemaTable();   

              foreach  (DataRow  row  in  schema.Rows)     
              {   
                    foreach  (DataColumn  col  in  schema.Columns)   
                          Console.WriteLine(col.DataType);   
              }   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top