Bulk insert from excel to sql for selective fields on the basis of cell locationFastest method to remove Empty rows and Columns From Excel Files using InteropInsert into … values ( SELECT … FROM … )SQLite - UPSERT *not* INSERT or REPLACEWhat is the best way to auto-generate INSERT statements for a SQL Server table?When should I use cross apply over inner join?SQL Server: How to Join to first rowHow do I UPDATE from a SELECT in SQL Server?Get all table names of a particular database by SQL query?What are the options for storing hierarchical data in a relational database?Reading excel rows from Execute sql task SSISReset identity seed after deleting records in SQL Server

Why doesn't Gödel's incompleteness theorem apply to false statements?

Sort with assumptions

Highest stage count that are used one right after the other?

Has the laser at Magurele, Romania reached a tenth of the Sun's power?

How can I, as DM, avoid the Conga Line of Death occurring when implementing some form of flanking rule?

How to split IPA spelling into syllables

What is the purpose of using a decision tree?

Does capillary rise violate hydrostatic paradox?

Is this saw blade faulty?

What is the tangent at a sharp point on a curve?

Why is indicated airspeed rather than ground speed used during the takeoff roll?

Friend wants my recommendation but I don't want to give it to him

Error in master's thesis, I do not know what to do

Why would five hundred and five same as one?

Can you take a "free object interaction" while incapacitated?

What is the meaning of "You've never met a graph you didn't like?"

Put the phone down / Put down the phone

Reason why a kingside attack is not justified

PTIJ: Which Dr. Seuss books should one obtain?

Do I have to take mana from my deck or hand when tapping this card?

Can you describe someone as luxurious? As in someone who likes luxurious things?

What properties make a magic weapon befit a Rogue more than a DEX-based Fighter?

Offset in split text content

Not hide and seek



Bulk insert from excel to sql for selective fields on the basis of cell location


Fastest method to remove Empty rows and Columns From Excel Files using InteropInsert into … values ( SELECT … FROM … )SQLite - UPSERT *not* INSERT or REPLACEWhat is the best way to auto-generate INSERT statements for a SQL Server table?When should I use cross apply over inner join?SQL Server: How to Join to first rowHow do I UPDATE from a SELECT in SQL Server?Get all table names of a particular database by SQL query?What are the options for storing hierarchical data in a relational database?Reading excel rows from Execute sql task SSISReset identity seed after deleting records in SQL Server













3















I have a SSIS package where I have to select some values from an excel sheet and insert them into a SQL Server database table, i am doing it through Execute sql task.



These are the steps:



  1. Select all records from mapping table, cell location is dynamic so keeping it in sql table (around 3000 cells are there - we have to pick value from selective fields in Excel and not all)

Example:



enter image description here



  1. Iterate through Foreach on each record



  2. Create a query with cell name and Sheet name



    Example: Select * from [GenDet$F3:F3]



  3. Execute the query to get that cell's value from Excel sheet


Example:



enter image description here



  1. Insert the values into the sql database table

enter image description here



It is working - but the problem is the time which it is taking. For 3000 fields, this whole process is taking 50 minutes to process one Excel file. I have to do this in less than a minute.



Please let me know the best approach to achieve this.



Thank you!










share|improve this question
























  • What are you doing for steps in the SSIS package? That seems important. Is this an Execute SQL task with a raw bulk insert query--and you're looping it over each field value? If you're using bulk insert on each data point individually that is most likely why it's taking 50 minutes.

    – Jacob H
    Mar 5 at 18:13











  • Also, please use character tables vs images. No one wants to retype your work to provide you answers.

    – KeithL
    Mar 5 at 18:45






  • 1





    I think that writing a c# script that read the data from excel cells and group them into a list or DataTable then perform a Bulk insert once will be more performant

    – Hadi
    Mar 5 at 21:17











  • Have you tried saving the Excel worksheet as a .csv file containing only the fields needed? SSIS should be able to ingest that quickly. Saving the Excel file can easily be scripted in PowerShell or VBA.

    – lit
    Mar 5 at 22:35












  • Yes I am doing it as an Execute Sql Task, I am not sure how to use bulk insert because the cells' location is dynamic and can change anytime so need to take it from Mapping table for each field.

    – Faizi
    Mar 6 at 6:20















3















I have a SSIS package where I have to select some values from an excel sheet and insert them into a SQL Server database table, i am doing it through Execute sql task.



These are the steps:



  1. Select all records from mapping table, cell location is dynamic so keeping it in sql table (around 3000 cells are there - we have to pick value from selective fields in Excel and not all)

Example:



enter image description here



  1. Iterate through Foreach on each record



  2. Create a query with cell name and Sheet name



    Example: Select * from [GenDet$F3:F3]



  3. Execute the query to get that cell's value from Excel sheet


Example:



enter image description here



  1. Insert the values into the sql database table

enter image description here



It is working - but the problem is the time which it is taking. For 3000 fields, this whole process is taking 50 minutes to process one Excel file. I have to do this in less than a minute.



Please let me know the best approach to achieve this.



Thank you!










share|improve this question
























  • What are you doing for steps in the SSIS package? That seems important. Is this an Execute SQL task with a raw bulk insert query--and you're looping it over each field value? If you're using bulk insert on each data point individually that is most likely why it's taking 50 minutes.

    – Jacob H
    Mar 5 at 18:13











  • Also, please use character tables vs images. No one wants to retype your work to provide you answers.

    – KeithL
    Mar 5 at 18:45






  • 1





    I think that writing a c# script that read the data from excel cells and group them into a list or DataTable then perform a Bulk insert once will be more performant

    – Hadi
    Mar 5 at 21:17











  • Have you tried saving the Excel worksheet as a .csv file containing only the fields needed? SSIS should be able to ingest that quickly. Saving the Excel file can easily be scripted in PowerShell or VBA.

    – lit
    Mar 5 at 22:35












  • Yes I am doing it as an Execute Sql Task, I am not sure how to use bulk insert because the cells' location is dynamic and can change anytime so need to take it from Mapping table for each field.

    – Faizi
    Mar 6 at 6:20













3












3








3








I have a SSIS package where I have to select some values from an excel sheet and insert them into a SQL Server database table, i am doing it through Execute sql task.



These are the steps:



  1. Select all records from mapping table, cell location is dynamic so keeping it in sql table (around 3000 cells are there - we have to pick value from selective fields in Excel and not all)

Example:



enter image description here



  1. Iterate through Foreach on each record



  2. Create a query with cell name and Sheet name



    Example: Select * from [GenDet$F3:F3]



  3. Execute the query to get that cell's value from Excel sheet


Example:



enter image description here



  1. Insert the values into the sql database table

enter image description here



It is working - but the problem is the time which it is taking. For 3000 fields, this whole process is taking 50 minutes to process one Excel file. I have to do this in less than a minute.



Please let me know the best approach to achieve this.



Thank you!










share|improve this question
















I have a SSIS package where I have to select some values from an excel sheet and insert them into a SQL Server database table, i am doing it through Execute sql task.



These are the steps:



  1. Select all records from mapping table, cell location is dynamic so keeping it in sql table (around 3000 cells are there - we have to pick value from selective fields in Excel and not all)

Example:



enter image description here



  1. Iterate through Foreach on each record



  2. Create a query with cell name and Sheet name



    Example: Select * from [GenDet$F3:F3]



  3. Execute the query to get that cell's value from Excel sheet


Example:



enter image description here



  1. Insert the values into the sql database table

enter image description here



It is working - but the problem is the time which it is taking. For 3000 fields, this whole process is taking 50 minutes to process one Excel file. I have to do this in less than a minute.



Please let me know the best approach to achieve this.



Thank you!







sql sql-server excel ssis etl






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 3 hours ago









Hadi

21.9k62974




21.9k62974










asked Mar 5 at 18:09









FaiziFaizi

183




183












  • What are you doing for steps in the SSIS package? That seems important. Is this an Execute SQL task with a raw bulk insert query--and you're looping it over each field value? If you're using bulk insert on each data point individually that is most likely why it's taking 50 minutes.

    – Jacob H
    Mar 5 at 18:13











  • Also, please use character tables vs images. No one wants to retype your work to provide you answers.

    – KeithL
    Mar 5 at 18:45






  • 1





    I think that writing a c# script that read the data from excel cells and group them into a list or DataTable then perform a Bulk insert once will be more performant

    – Hadi
    Mar 5 at 21:17











  • Have you tried saving the Excel worksheet as a .csv file containing only the fields needed? SSIS should be able to ingest that quickly. Saving the Excel file can easily be scripted in PowerShell or VBA.

    – lit
    Mar 5 at 22:35












  • Yes I am doing it as an Execute Sql Task, I am not sure how to use bulk insert because the cells' location is dynamic and can change anytime so need to take it from Mapping table for each field.

    – Faizi
    Mar 6 at 6:20

















  • What are you doing for steps in the SSIS package? That seems important. Is this an Execute SQL task with a raw bulk insert query--and you're looping it over each field value? If you're using bulk insert on each data point individually that is most likely why it's taking 50 minutes.

    – Jacob H
    Mar 5 at 18:13











  • Also, please use character tables vs images. No one wants to retype your work to provide you answers.

    – KeithL
    Mar 5 at 18:45






  • 1





    I think that writing a c# script that read the data from excel cells and group them into a list or DataTable then perform a Bulk insert once will be more performant

    – Hadi
    Mar 5 at 21:17











  • Have you tried saving the Excel worksheet as a .csv file containing only the fields needed? SSIS should be able to ingest that quickly. Saving the Excel file can easily be scripted in PowerShell or VBA.

    – lit
    Mar 5 at 22:35












  • Yes I am doing it as an Execute Sql Task, I am not sure how to use bulk insert because the cells' location is dynamic and can change anytime so need to take it from Mapping table for each field.

    – Faizi
    Mar 6 at 6:20
















What are you doing for steps in the SSIS package? That seems important. Is this an Execute SQL task with a raw bulk insert query--and you're looping it over each field value? If you're using bulk insert on each data point individually that is most likely why it's taking 50 minutes.

– Jacob H
Mar 5 at 18:13





What are you doing for steps in the SSIS package? That seems important. Is this an Execute SQL task with a raw bulk insert query--and you're looping it over each field value? If you're using bulk insert on each data point individually that is most likely why it's taking 50 minutes.

– Jacob H
Mar 5 at 18:13













Also, please use character tables vs images. No one wants to retype your work to provide you answers.

– KeithL
Mar 5 at 18:45





Also, please use character tables vs images. No one wants to retype your work to provide you answers.

– KeithL
Mar 5 at 18:45




1




1





I think that writing a c# script that read the data from excel cells and group them into a list or DataTable then perform a Bulk insert once will be more performant

– Hadi
Mar 5 at 21:17





I think that writing a c# script that read the data from excel cells and group them into a list or DataTable then perform a Bulk insert once will be more performant

– Hadi
Mar 5 at 21:17













Have you tried saving the Excel worksheet as a .csv file containing only the fields needed? SSIS should be able to ingest that quickly. Saving the Excel file can easily be scripted in PowerShell or VBA.

– lit
Mar 5 at 22:35






Have you tried saving the Excel worksheet as a .csv file containing only the fields needed? SSIS should be able to ingest that quickly. Saving the Excel file can easily be scripted in PowerShell or VBA.

– lit
Mar 5 at 22:35














Yes I am doing it as an Execute Sql Task, I am not sure how to use bulk insert because the cells' location is dynamic and can change anytime so need to take it from Mapping table for each field.

– Faizi
Mar 6 at 6:20





Yes I am doing it as an Execute Sql Task, I am not sure how to use bulk insert because the cells' location is dynamic and can change anytime so need to take it from Mapping table for each field.

– Faizi
Mar 6 at 6:20












2 Answers
2






active

oldest

votes


















1














As i mentioned in the comments, I think that writing a c# script that read the data from excel cells and group them into a list or DataTable then perform a Bulk insert once will be more performant



C# application/script task



Needed assemblies



First you have to import Excel Interop assembly:



using Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;


Convert column header letter to index



Now you should define the following function that convert the excel column alphabet to index:



private int ParseColHeaderToIndex(string colAdress)

int[] digits = new int[colAdress.Length];
for (int i = 0; i < colAdress.Length; i++)

digits[i] = Convert.ToInt32(colAdress[i]) - 64;

int mul = 1;
int res = 0;
for (int pos = digits.Length - 1; pos >= 0; pos--)

res += digits[pos] * mul;
mul *= 26;

return res;



SQL bulk insert function



The following function is to perform bulk insert operation into SQL



public void InsertToSQLUsingSQLBulk(System.Data.DataTable dt, string connectionstring, string Tablename)



try

using (var bulkCopy = new SqlBulkCopy(connectionstring, SqlBulkCopyOptions.KeepIdentity))


foreach (DataColumn col in dt.Columns)

bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);


bulkCopy.BulkCopyTimeout = 600;
bulkCopy.DestinationTableName = Tablename;
bulkCopy.WriteToServer(dt);



catch (Exception ex)

throw ex;




Reading from excel into destination DataTable



The following function takes the excel path and the ranges DataTable as parameter and return a DataTable having the destination structure (Id, AttributeKey, AttributeValue)



public System.Data.DataTable ReadFromExcel(System.Data.DataTable dtRanges,string strPath)


string num = "0123456789";

//Declare result datatable
System.Data.DataTable destination = new System.Data.DataTable();
destination.Columns.Add("Id");
destination.Columns.Add("AttributeKey");
destination.Columns.Add("AttributeValue");

//Decalre Interop Objects
Microsoft.Office.Interop.Excel.Application m_XlApp;
m_XlApp = new Microsoft.Office.Interop.Excel.Application();
m_XlApp.Visible = false;
m_XlApp.DisplayAlerts = false;

Workbook xlWbs = null;
xlWbs = m_XlApp.Workbooks.Open(strPath, Type.Missing, Type.Missing,
Type.Missing, "'", Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);

xlWbs.DoNotPromptForConvert = true;
xlWbs.CheckCompatibility = false;
xlWbs.Application.DisplayAlerts = false;

//Loop over worksheets
foreach (Worksheet xlWks in xlWbs.Worksheets)

string Name = xlWks.Name;

//Assing rows relevant to the current sheet

foreach (DataRow drRow in dtRanges.AsEnumerable().Where(x => x["Sheet_Name"].ToString() == Name))


string sheet = drRow["Sheet_Name"].ToString();
string range = drRow["Location_Value"].ToString();
string field = drRow["Field_Name"].ToString();
string id = drRow["Id"].ToString();
string rangeAlpha = range.Split(':')[0];
int rowidx = 0;
int colidx = 0;



foreach (char chr in num)
rangeAlpha = rangeAlpha.Replace(chr, '');


rowidx = Int32.Parse(range.Split(':')[0].Replace(rangeAlpha, ""));
colidx = ParseColHeaderToIndex(rangeAlpha);


DataRow dr = destination.NewRow();

if (xlWks.Cells[rowidx, colidx] != null && (xlWks.Cells[rowidx, colidx] as Range).Value2 != null)


dr["AttributeValue"] = (string)(xlWks.Cells[rowidx, colidx] as Range).Value2;

else

dr["AttributeValue"] = "";




dr["AttributeKey"] = drRow["Field_Name"].ToString();
dr["Id"] = drRow["Id"].ToString();

destination.Rows.Add(dr);




xlWbs.Close(false, Type.Missing, Type.Missing);
m_XlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWbs);
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_XlApp);


return destination;




Main program



public void Main()

//Initialize ranges table
System.Data.DataTable ranges = new System.Data.DataTable();
ranges.Columns.Add("Id");
ranges.Columns.Add("Field_Name");
ranges.Columns.Add("Location_Value");
ranges.Columns.Add("Sheet_Name");

//Add rows or read them from database using SQLDataAdapter


//note that the destination table must exists in the database with identical columns of datatable

System.Data.DataTable destination = ReadFromExcel(ranges, "C:\1.xlsx", "dbo.destination");

InsertToSQLUsingSQLBulk(destination, "Pass SQL Server destination connection string here");







Update 1 - Improve performance



You can improve the method performance by putting all worksheet contents inside an two dimension array, then loop over array instead of looping inside the Excel worksheet.



Excel.Range targetCells = xlWks.UsedRange;
object[,] allValues = (object[,])targetCells.Cells.Value;

...


if (targetCells.Cells[rowidx, colidx] != null)


dr["AttributeValue"] = (string)(targetCells.Cells[rowidx, colidx] as Range).Value2;

else

dr["AttributeValue"] = "";



Reference



  • Fastest method to remove Empty rows and Columns From Excel Files using Interop





share|improve this answer




















  • 1





    Thank you so much Hadi for such elaborated solution, I am implementing it and will let u know about the outcome.

    – Faizi
    Mar 8 at 15:58











  • @Faizi check my answer update, you might find it interesting

    – Hadi
    Mar 12 at 19:25


















1














How about considering building one select statement to run that gets all the records at once.



Based on your image, something like this:



select
(Select [Field1] from [GenDet$I3:I3]) as Field1
,(Select [Field2] from [GenDet$I4:I4]) as Field2
...


That was horizontal and column based.



or you can go vertical with



 (Select [FieldName],[Field1] as Value from [GenDet$I3:I3]) as Field1
union all
(Select [Field2],* from [GenDet$I4:I4]) as Field2
...


I know there are 3000 or so but you can build this with a string concatenation query rather simply.



Just a thought.



This would decrease execution time as the spreadsheet is not opening and closing on every iteration.






share|improve this answer























  • When using OleDb to connection to excel or access there is a limit of allowed UNION operation (i think maximum 16 UNION) so it will not work in this case

    – Hadi
    Mar 5 at 20:49











  • The cells location is dynamic so i cannot keep it static in queries, its a compulsion to take location of each field from mapping table.

    – Faizi
    Mar 6 at 6:22











  • I'm suggesting that you build the query through string concatenation query id the mapping table

    – KeithL
    Mar 6 at 12:05











  • But Hadi makes a good point. I'd rather both this in c#. Read mapping table into data table. Then loop thru that inside a using statement to read from excel directly to a data flow. That's not easy to do but it's a good option.

    – KeithL
    Mar 6 at 12:09











  • @KeithL i tried to write an C# application check my answer and i am open for any suggestions

    – Hadi
    Mar 7 at 0:59










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55009040%2fbulk-insert-from-excel-to-sql-for-selective-fields-on-the-basis-of-cell-location%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














As i mentioned in the comments, I think that writing a c# script that read the data from excel cells and group them into a list or DataTable then perform a Bulk insert once will be more performant



C# application/script task



Needed assemblies



First you have to import Excel Interop assembly:



using Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;


Convert column header letter to index



Now you should define the following function that convert the excel column alphabet to index:



private int ParseColHeaderToIndex(string colAdress)

int[] digits = new int[colAdress.Length];
for (int i = 0; i < colAdress.Length; i++)

digits[i] = Convert.ToInt32(colAdress[i]) - 64;

int mul = 1;
int res = 0;
for (int pos = digits.Length - 1; pos >= 0; pos--)

res += digits[pos] * mul;
mul *= 26;

return res;



SQL bulk insert function



The following function is to perform bulk insert operation into SQL



public void InsertToSQLUsingSQLBulk(System.Data.DataTable dt, string connectionstring, string Tablename)



try

using (var bulkCopy = new SqlBulkCopy(connectionstring, SqlBulkCopyOptions.KeepIdentity))


foreach (DataColumn col in dt.Columns)

bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);


bulkCopy.BulkCopyTimeout = 600;
bulkCopy.DestinationTableName = Tablename;
bulkCopy.WriteToServer(dt);



catch (Exception ex)

throw ex;




Reading from excel into destination DataTable



The following function takes the excel path and the ranges DataTable as parameter and return a DataTable having the destination structure (Id, AttributeKey, AttributeValue)



public System.Data.DataTable ReadFromExcel(System.Data.DataTable dtRanges,string strPath)


string num = "0123456789";

//Declare result datatable
System.Data.DataTable destination = new System.Data.DataTable();
destination.Columns.Add("Id");
destination.Columns.Add("AttributeKey");
destination.Columns.Add("AttributeValue");

//Decalre Interop Objects
Microsoft.Office.Interop.Excel.Application m_XlApp;
m_XlApp = new Microsoft.Office.Interop.Excel.Application();
m_XlApp.Visible = false;
m_XlApp.DisplayAlerts = false;

Workbook xlWbs = null;
xlWbs = m_XlApp.Workbooks.Open(strPath, Type.Missing, Type.Missing,
Type.Missing, "'", Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);

xlWbs.DoNotPromptForConvert = true;
xlWbs.CheckCompatibility = false;
xlWbs.Application.DisplayAlerts = false;

//Loop over worksheets
foreach (Worksheet xlWks in xlWbs.Worksheets)

string Name = xlWks.Name;

//Assing rows relevant to the current sheet

foreach (DataRow drRow in dtRanges.AsEnumerable().Where(x => x["Sheet_Name"].ToString() == Name))


string sheet = drRow["Sheet_Name"].ToString();
string range = drRow["Location_Value"].ToString();
string field = drRow["Field_Name"].ToString();
string id = drRow["Id"].ToString();
string rangeAlpha = range.Split(':')[0];
int rowidx = 0;
int colidx = 0;



foreach (char chr in num)
rangeAlpha = rangeAlpha.Replace(chr, '');


rowidx = Int32.Parse(range.Split(':')[0].Replace(rangeAlpha, ""));
colidx = ParseColHeaderToIndex(rangeAlpha);


DataRow dr = destination.NewRow();

if (xlWks.Cells[rowidx, colidx] != null && (xlWks.Cells[rowidx, colidx] as Range).Value2 != null)


dr["AttributeValue"] = (string)(xlWks.Cells[rowidx, colidx] as Range).Value2;

else

dr["AttributeValue"] = "";




dr["AttributeKey"] = drRow["Field_Name"].ToString();
dr["Id"] = drRow["Id"].ToString();

destination.Rows.Add(dr);




xlWbs.Close(false, Type.Missing, Type.Missing);
m_XlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWbs);
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_XlApp);


return destination;




Main program



public void Main()

//Initialize ranges table
System.Data.DataTable ranges = new System.Data.DataTable();
ranges.Columns.Add("Id");
ranges.Columns.Add("Field_Name");
ranges.Columns.Add("Location_Value");
ranges.Columns.Add("Sheet_Name");

//Add rows or read them from database using SQLDataAdapter


//note that the destination table must exists in the database with identical columns of datatable

System.Data.DataTable destination = ReadFromExcel(ranges, "C:\1.xlsx", "dbo.destination");

InsertToSQLUsingSQLBulk(destination, "Pass SQL Server destination connection string here");







Update 1 - Improve performance



You can improve the method performance by putting all worksheet contents inside an two dimension array, then loop over array instead of looping inside the Excel worksheet.



Excel.Range targetCells = xlWks.UsedRange;
object[,] allValues = (object[,])targetCells.Cells.Value;

...


if (targetCells.Cells[rowidx, colidx] != null)


dr["AttributeValue"] = (string)(targetCells.Cells[rowidx, colidx] as Range).Value2;

else

dr["AttributeValue"] = "";



Reference



  • Fastest method to remove Empty rows and Columns From Excel Files using Interop





share|improve this answer




















  • 1





    Thank you so much Hadi for such elaborated solution, I am implementing it and will let u know about the outcome.

    – Faizi
    Mar 8 at 15:58











  • @Faizi check my answer update, you might find it interesting

    – Hadi
    Mar 12 at 19:25















1














As i mentioned in the comments, I think that writing a c# script that read the data from excel cells and group them into a list or DataTable then perform a Bulk insert once will be more performant



C# application/script task



Needed assemblies



First you have to import Excel Interop assembly:



using Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;


Convert column header letter to index



Now you should define the following function that convert the excel column alphabet to index:



private int ParseColHeaderToIndex(string colAdress)

int[] digits = new int[colAdress.Length];
for (int i = 0; i < colAdress.Length; i++)

digits[i] = Convert.ToInt32(colAdress[i]) - 64;

int mul = 1;
int res = 0;
for (int pos = digits.Length - 1; pos >= 0; pos--)

res += digits[pos] * mul;
mul *= 26;

return res;



SQL bulk insert function



The following function is to perform bulk insert operation into SQL



public void InsertToSQLUsingSQLBulk(System.Data.DataTable dt, string connectionstring, string Tablename)



try

using (var bulkCopy = new SqlBulkCopy(connectionstring, SqlBulkCopyOptions.KeepIdentity))


foreach (DataColumn col in dt.Columns)

bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);


bulkCopy.BulkCopyTimeout = 600;
bulkCopy.DestinationTableName = Tablename;
bulkCopy.WriteToServer(dt);



catch (Exception ex)

throw ex;




Reading from excel into destination DataTable



The following function takes the excel path and the ranges DataTable as parameter and return a DataTable having the destination structure (Id, AttributeKey, AttributeValue)



public System.Data.DataTable ReadFromExcel(System.Data.DataTable dtRanges,string strPath)


string num = "0123456789";

//Declare result datatable
System.Data.DataTable destination = new System.Data.DataTable();
destination.Columns.Add("Id");
destination.Columns.Add("AttributeKey");
destination.Columns.Add("AttributeValue");

//Decalre Interop Objects
Microsoft.Office.Interop.Excel.Application m_XlApp;
m_XlApp = new Microsoft.Office.Interop.Excel.Application();
m_XlApp.Visible = false;
m_XlApp.DisplayAlerts = false;

Workbook xlWbs = null;
xlWbs = m_XlApp.Workbooks.Open(strPath, Type.Missing, Type.Missing,
Type.Missing, "'", Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);

xlWbs.DoNotPromptForConvert = true;
xlWbs.CheckCompatibility = false;
xlWbs.Application.DisplayAlerts = false;

//Loop over worksheets
foreach (Worksheet xlWks in xlWbs.Worksheets)

string Name = xlWks.Name;

//Assing rows relevant to the current sheet

foreach (DataRow drRow in dtRanges.AsEnumerable().Where(x => x["Sheet_Name"].ToString() == Name))


string sheet = drRow["Sheet_Name"].ToString();
string range = drRow["Location_Value"].ToString();
string field = drRow["Field_Name"].ToString();
string id = drRow["Id"].ToString();
string rangeAlpha = range.Split(':')[0];
int rowidx = 0;
int colidx = 0;



foreach (char chr in num)
rangeAlpha = rangeAlpha.Replace(chr, '');


rowidx = Int32.Parse(range.Split(':')[0].Replace(rangeAlpha, ""));
colidx = ParseColHeaderToIndex(rangeAlpha);


DataRow dr = destination.NewRow();

if (xlWks.Cells[rowidx, colidx] != null && (xlWks.Cells[rowidx, colidx] as Range).Value2 != null)


dr["AttributeValue"] = (string)(xlWks.Cells[rowidx, colidx] as Range).Value2;

else

dr["AttributeValue"] = "";




dr["AttributeKey"] = drRow["Field_Name"].ToString();
dr["Id"] = drRow["Id"].ToString();

destination.Rows.Add(dr);




xlWbs.Close(false, Type.Missing, Type.Missing);
m_XlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWbs);
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_XlApp);


return destination;




Main program



public void Main()

//Initialize ranges table
System.Data.DataTable ranges = new System.Data.DataTable();
ranges.Columns.Add("Id");
ranges.Columns.Add("Field_Name");
ranges.Columns.Add("Location_Value");
ranges.Columns.Add("Sheet_Name");

//Add rows or read them from database using SQLDataAdapter


//note that the destination table must exists in the database with identical columns of datatable

System.Data.DataTable destination = ReadFromExcel(ranges, "C:\1.xlsx", "dbo.destination");

InsertToSQLUsingSQLBulk(destination, "Pass SQL Server destination connection string here");







Update 1 - Improve performance



You can improve the method performance by putting all worksheet contents inside an two dimension array, then loop over array instead of looping inside the Excel worksheet.



Excel.Range targetCells = xlWks.UsedRange;
object[,] allValues = (object[,])targetCells.Cells.Value;

...


if (targetCells.Cells[rowidx, colidx] != null)


dr["AttributeValue"] = (string)(targetCells.Cells[rowidx, colidx] as Range).Value2;

else

dr["AttributeValue"] = "";



Reference



  • Fastest method to remove Empty rows and Columns From Excel Files using Interop





share|improve this answer




















  • 1





    Thank you so much Hadi for such elaborated solution, I am implementing it and will let u know about the outcome.

    – Faizi
    Mar 8 at 15:58











  • @Faizi check my answer update, you might find it interesting

    – Hadi
    Mar 12 at 19:25













1












1








1







As i mentioned in the comments, I think that writing a c# script that read the data from excel cells and group them into a list or DataTable then perform a Bulk insert once will be more performant



C# application/script task



Needed assemblies



First you have to import Excel Interop assembly:



using Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;


Convert column header letter to index



Now you should define the following function that convert the excel column alphabet to index:



private int ParseColHeaderToIndex(string colAdress)

int[] digits = new int[colAdress.Length];
for (int i = 0; i < colAdress.Length; i++)

digits[i] = Convert.ToInt32(colAdress[i]) - 64;

int mul = 1;
int res = 0;
for (int pos = digits.Length - 1; pos >= 0; pos--)

res += digits[pos] * mul;
mul *= 26;

return res;



SQL bulk insert function



The following function is to perform bulk insert operation into SQL



public void InsertToSQLUsingSQLBulk(System.Data.DataTable dt, string connectionstring, string Tablename)



try

using (var bulkCopy = new SqlBulkCopy(connectionstring, SqlBulkCopyOptions.KeepIdentity))


foreach (DataColumn col in dt.Columns)

bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);


bulkCopy.BulkCopyTimeout = 600;
bulkCopy.DestinationTableName = Tablename;
bulkCopy.WriteToServer(dt);



catch (Exception ex)

throw ex;




Reading from excel into destination DataTable



The following function takes the excel path and the ranges DataTable as parameter and return a DataTable having the destination structure (Id, AttributeKey, AttributeValue)



public System.Data.DataTable ReadFromExcel(System.Data.DataTable dtRanges,string strPath)


string num = "0123456789";

//Declare result datatable
System.Data.DataTable destination = new System.Data.DataTable();
destination.Columns.Add("Id");
destination.Columns.Add("AttributeKey");
destination.Columns.Add("AttributeValue");

//Decalre Interop Objects
Microsoft.Office.Interop.Excel.Application m_XlApp;
m_XlApp = new Microsoft.Office.Interop.Excel.Application();
m_XlApp.Visible = false;
m_XlApp.DisplayAlerts = false;

Workbook xlWbs = null;
xlWbs = m_XlApp.Workbooks.Open(strPath, Type.Missing, Type.Missing,
Type.Missing, "'", Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);

xlWbs.DoNotPromptForConvert = true;
xlWbs.CheckCompatibility = false;
xlWbs.Application.DisplayAlerts = false;

//Loop over worksheets
foreach (Worksheet xlWks in xlWbs.Worksheets)

string Name = xlWks.Name;

//Assing rows relevant to the current sheet

foreach (DataRow drRow in dtRanges.AsEnumerable().Where(x => x["Sheet_Name"].ToString() == Name))


string sheet = drRow["Sheet_Name"].ToString();
string range = drRow["Location_Value"].ToString();
string field = drRow["Field_Name"].ToString();
string id = drRow["Id"].ToString();
string rangeAlpha = range.Split(':')[0];
int rowidx = 0;
int colidx = 0;



foreach (char chr in num)
rangeAlpha = rangeAlpha.Replace(chr, '');


rowidx = Int32.Parse(range.Split(':')[0].Replace(rangeAlpha, ""));
colidx = ParseColHeaderToIndex(rangeAlpha);


DataRow dr = destination.NewRow();

if (xlWks.Cells[rowidx, colidx] != null && (xlWks.Cells[rowidx, colidx] as Range).Value2 != null)


dr["AttributeValue"] = (string)(xlWks.Cells[rowidx, colidx] as Range).Value2;

else

dr["AttributeValue"] = "";




dr["AttributeKey"] = drRow["Field_Name"].ToString();
dr["Id"] = drRow["Id"].ToString();

destination.Rows.Add(dr);




xlWbs.Close(false, Type.Missing, Type.Missing);
m_XlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWbs);
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_XlApp);


return destination;




Main program



public void Main()

//Initialize ranges table
System.Data.DataTable ranges = new System.Data.DataTable();
ranges.Columns.Add("Id");
ranges.Columns.Add("Field_Name");
ranges.Columns.Add("Location_Value");
ranges.Columns.Add("Sheet_Name");

//Add rows or read them from database using SQLDataAdapter


//note that the destination table must exists in the database with identical columns of datatable

System.Data.DataTable destination = ReadFromExcel(ranges, "C:\1.xlsx", "dbo.destination");

InsertToSQLUsingSQLBulk(destination, "Pass SQL Server destination connection string here");







Update 1 - Improve performance



You can improve the method performance by putting all worksheet contents inside an two dimension array, then loop over array instead of looping inside the Excel worksheet.



Excel.Range targetCells = xlWks.UsedRange;
object[,] allValues = (object[,])targetCells.Cells.Value;

...


if (targetCells.Cells[rowidx, colidx] != null)


dr["AttributeValue"] = (string)(targetCells.Cells[rowidx, colidx] as Range).Value2;

else

dr["AttributeValue"] = "";



Reference



  • Fastest method to remove Empty rows and Columns From Excel Files using Interop





share|improve this answer















As i mentioned in the comments, I think that writing a c# script that read the data from excel cells and group them into a list or DataTable then perform a Bulk insert once will be more performant



C# application/script task



Needed assemblies



First you have to import Excel Interop assembly:



using Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;


Convert column header letter to index



Now you should define the following function that convert the excel column alphabet to index:



private int ParseColHeaderToIndex(string colAdress)

int[] digits = new int[colAdress.Length];
for (int i = 0; i < colAdress.Length; i++)

digits[i] = Convert.ToInt32(colAdress[i]) - 64;

int mul = 1;
int res = 0;
for (int pos = digits.Length - 1; pos >= 0; pos--)

res += digits[pos] * mul;
mul *= 26;

return res;



SQL bulk insert function



The following function is to perform bulk insert operation into SQL



public void InsertToSQLUsingSQLBulk(System.Data.DataTable dt, string connectionstring, string Tablename)



try

using (var bulkCopy = new SqlBulkCopy(connectionstring, SqlBulkCopyOptions.KeepIdentity))


foreach (DataColumn col in dt.Columns)

bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);


bulkCopy.BulkCopyTimeout = 600;
bulkCopy.DestinationTableName = Tablename;
bulkCopy.WriteToServer(dt);



catch (Exception ex)

throw ex;




Reading from excel into destination DataTable



The following function takes the excel path and the ranges DataTable as parameter and return a DataTable having the destination structure (Id, AttributeKey, AttributeValue)



public System.Data.DataTable ReadFromExcel(System.Data.DataTable dtRanges,string strPath)


string num = "0123456789";

//Declare result datatable
System.Data.DataTable destination = new System.Data.DataTable();
destination.Columns.Add("Id");
destination.Columns.Add("AttributeKey");
destination.Columns.Add("AttributeValue");

//Decalre Interop Objects
Microsoft.Office.Interop.Excel.Application m_XlApp;
m_XlApp = new Microsoft.Office.Interop.Excel.Application();
m_XlApp.Visible = false;
m_XlApp.DisplayAlerts = false;

Workbook xlWbs = null;
xlWbs = m_XlApp.Workbooks.Open(strPath, Type.Missing, Type.Missing,
Type.Missing, "'", Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);

xlWbs.DoNotPromptForConvert = true;
xlWbs.CheckCompatibility = false;
xlWbs.Application.DisplayAlerts = false;

//Loop over worksheets
foreach (Worksheet xlWks in xlWbs.Worksheets)

string Name = xlWks.Name;

//Assing rows relevant to the current sheet

foreach (DataRow drRow in dtRanges.AsEnumerable().Where(x => x["Sheet_Name"].ToString() == Name))


string sheet = drRow["Sheet_Name"].ToString();
string range = drRow["Location_Value"].ToString();
string field = drRow["Field_Name"].ToString();
string id = drRow["Id"].ToString();
string rangeAlpha = range.Split(':')[0];
int rowidx = 0;
int colidx = 0;



foreach (char chr in num)
rangeAlpha = rangeAlpha.Replace(chr, '');


rowidx = Int32.Parse(range.Split(':')[0].Replace(rangeAlpha, ""));
colidx = ParseColHeaderToIndex(rangeAlpha);


DataRow dr = destination.NewRow();

if (xlWks.Cells[rowidx, colidx] != null && (xlWks.Cells[rowidx, colidx] as Range).Value2 != null)


dr["AttributeValue"] = (string)(xlWks.Cells[rowidx, colidx] as Range).Value2;

else

dr["AttributeValue"] = "";




dr["AttributeKey"] = drRow["Field_Name"].ToString();
dr["Id"] = drRow["Id"].ToString();

destination.Rows.Add(dr);




xlWbs.Close(false, Type.Missing, Type.Missing);
m_XlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWbs);
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_XlApp);


return destination;




Main program



public void Main()

//Initialize ranges table
System.Data.DataTable ranges = new System.Data.DataTable();
ranges.Columns.Add("Id");
ranges.Columns.Add("Field_Name");
ranges.Columns.Add("Location_Value");
ranges.Columns.Add("Sheet_Name");

//Add rows or read them from database using SQLDataAdapter


//note that the destination table must exists in the database with identical columns of datatable

System.Data.DataTable destination = ReadFromExcel(ranges, "C:\1.xlsx", "dbo.destination");

InsertToSQLUsingSQLBulk(destination, "Pass SQL Server destination connection string here");







Update 1 - Improve performance



You can improve the method performance by putting all worksheet contents inside an two dimension array, then loop over array instead of looping inside the Excel worksheet.



Excel.Range targetCells = xlWks.UsedRange;
object[,] allValues = (object[,])targetCells.Cells.Value;

...


if (targetCells.Cells[rowidx, colidx] != null)


dr["AttributeValue"] = (string)(targetCells.Cells[rowidx, colidx] as Range).Value2;

else

dr["AttributeValue"] = "";



Reference



  • Fastest method to remove Empty rows and Columns From Excel Files using Interop






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 12 at 19:25

























answered Mar 7 at 0:59









HadiHadi

21.9k62974




21.9k62974







  • 1





    Thank you so much Hadi for such elaborated solution, I am implementing it and will let u know about the outcome.

    – Faizi
    Mar 8 at 15:58











  • @Faizi check my answer update, you might find it interesting

    – Hadi
    Mar 12 at 19:25












  • 1





    Thank you so much Hadi for such elaborated solution, I am implementing it and will let u know about the outcome.

    – Faizi
    Mar 8 at 15:58











  • @Faizi check my answer update, you might find it interesting

    – Hadi
    Mar 12 at 19:25







1




1





Thank you so much Hadi for such elaborated solution, I am implementing it and will let u know about the outcome.

– Faizi
Mar 8 at 15:58





Thank you so much Hadi for such elaborated solution, I am implementing it and will let u know about the outcome.

– Faizi
Mar 8 at 15:58













@Faizi check my answer update, you might find it interesting

– Hadi
Mar 12 at 19:25





@Faizi check my answer update, you might find it interesting

– Hadi
Mar 12 at 19:25













1














How about considering building one select statement to run that gets all the records at once.



Based on your image, something like this:



select
(Select [Field1] from [GenDet$I3:I3]) as Field1
,(Select [Field2] from [GenDet$I4:I4]) as Field2
...


That was horizontal and column based.



or you can go vertical with



 (Select [FieldName],[Field1] as Value from [GenDet$I3:I3]) as Field1
union all
(Select [Field2],* from [GenDet$I4:I4]) as Field2
...


I know there are 3000 or so but you can build this with a string concatenation query rather simply.



Just a thought.



This would decrease execution time as the spreadsheet is not opening and closing on every iteration.






share|improve this answer























  • When using OleDb to connection to excel or access there is a limit of allowed UNION operation (i think maximum 16 UNION) so it will not work in this case

    – Hadi
    Mar 5 at 20:49











  • The cells location is dynamic so i cannot keep it static in queries, its a compulsion to take location of each field from mapping table.

    – Faizi
    Mar 6 at 6:22











  • I'm suggesting that you build the query through string concatenation query id the mapping table

    – KeithL
    Mar 6 at 12:05











  • But Hadi makes a good point. I'd rather both this in c#. Read mapping table into data table. Then loop thru that inside a using statement to read from excel directly to a data flow. That's not easy to do but it's a good option.

    – KeithL
    Mar 6 at 12:09











  • @KeithL i tried to write an C# application check my answer and i am open for any suggestions

    – Hadi
    Mar 7 at 0:59















1














How about considering building one select statement to run that gets all the records at once.



Based on your image, something like this:



select
(Select [Field1] from [GenDet$I3:I3]) as Field1
,(Select [Field2] from [GenDet$I4:I4]) as Field2
...


That was horizontal and column based.



or you can go vertical with



 (Select [FieldName],[Field1] as Value from [GenDet$I3:I3]) as Field1
union all
(Select [Field2],* from [GenDet$I4:I4]) as Field2
...


I know there are 3000 or so but you can build this with a string concatenation query rather simply.



Just a thought.



This would decrease execution time as the spreadsheet is not opening and closing on every iteration.






share|improve this answer























  • When using OleDb to connection to excel or access there is a limit of allowed UNION operation (i think maximum 16 UNION) so it will not work in this case

    – Hadi
    Mar 5 at 20:49











  • The cells location is dynamic so i cannot keep it static in queries, its a compulsion to take location of each field from mapping table.

    – Faizi
    Mar 6 at 6:22











  • I'm suggesting that you build the query through string concatenation query id the mapping table

    – KeithL
    Mar 6 at 12:05











  • But Hadi makes a good point. I'd rather both this in c#. Read mapping table into data table. Then loop thru that inside a using statement to read from excel directly to a data flow. That's not easy to do but it's a good option.

    – KeithL
    Mar 6 at 12:09











  • @KeithL i tried to write an C# application check my answer and i am open for any suggestions

    – Hadi
    Mar 7 at 0:59













1












1








1







How about considering building one select statement to run that gets all the records at once.



Based on your image, something like this:



select
(Select [Field1] from [GenDet$I3:I3]) as Field1
,(Select [Field2] from [GenDet$I4:I4]) as Field2
...


That was horizontal and column based.



or you can go vertical with



 (Select [FieldName],[Field1] as Value from [GenDet$I3:I3]) as Field1
union all
(Select [Field2],* from [GenDet$I4:I4]) as Field2
...


I know there are 3000 or so but you can build this with a string concatenation query rather simply.



Just a thought.



This would decrease execution time as the spreadsheet is not opening and closing on every iteration.






share|improve this answer













How about considering building one select statement to run that gets all the records at once.



Based on your image, something like this:



select
(Select [Field1] from [GenDet$I3:I3]) as Field1
,(Select [Field2] from [GenDet$I4:I4]) as Field2
...


That was horizontal and column based.



or you can go vertical with



 (Select [FieldName],[Field1] as Value from [GenDet$I3:I3]) as Field1
union all
(Select [Field2],* from [GenDet$I4:I4]) as Field2
...


I know there are 3000 or so but you can build this with a string concatenation query rather simply.



Just a thought.



This would decrease execution time as the spreadsheet is not opening and closing on every iteration.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 5 at 18:41









KeithLKeithL

2,5881715




2,5881715












  • When using OleDb to connection to excel or access there is a limit of allowed UNION operation (i think maximum 16 UNION) so it will not work in this case

    – Hadi
    Mar 5 at 20:49











  • The cells location is dynamic so i cannot keep it static in queries, its a compulsion to take location of each field from mapping table.

    – Faizi
    Mar 6 at 6:22











  • I'm suggesting that you build the query through string concatenation query id the mapping table

    – KeithL
    Mar 6 at 12:05











  • But Hadi makes a good point. I'd rather both this in c#. Read mapping table into data table. Then loop thru that inside a using statement to read from excel directly to a data flow. That's not easy to do but it's a good option.

    – KeithL
    Mar 6 at 12:09











  • @KeithL i tried to write an C# application check my answer and i am open for any suggestions

    – Hadi
    Mar 7 at 0:59

















  • When using OleDb to connection to excel or access there is a limit of allowed UNION operation (i think maximum 16 UNION) so it will not work in this case

    – Hadi
    Mar 5 at 20:49











  • The cells location is dynamic so i cannot keep it static in queries, its a compulsion to take location of each field from mapping table.

    – Faizi
    Mar 6 at 6:22











  • I'm suggesting that you build the query through string concatenation query id the mapping table

    – KeithL
    Mar 6 at 12:05











  • But Hadi makes a good point. I'd rather both this in c#. Read mapping table into data table. Then loop thru that inside a using statement to read from excel directly to a data flow. That's not easy to do but it's a good option.

    – KeithL
    Mar 6 at 12:09











  • @KeithL i tried to write an C# application check my answer and i am open for any suggestions

    – Hadi
    Mar 7 at 0:59
















When using OleDb to connection to excel or access there is a limit of allowed UNION operation (i think maximum 16 UNION) so it will not work in this case

– Hadi
Mar 5 at 20:49





When using OleDb to connection to excel or access there is a limit of allowed UNION operation (i think maximum 16 UNION) so it will not work in this case

– Hadi
Mar 5 at 20:49













The cells location is dynamic so i cannot keep it static in queries, its a compulsion to take location of each field from mapping table.

– Faizi
Mar 6 at 6:22





The cells location is dynamic so i cannot keep it static in queries, its a compulsion to take location of each field from mapping table.

– Faizi
Mar 6 at 6:22













I'm suggesting that you build the query through string concatenation query id the mapping table

– KeithL
Mar 6 at 12:05





I'm suggesting that you build the query through string concatenation query id the mapping table

– KeithL
Mar 6 at 12:05













But Hadi makes a good point. I'd rather both this in c#. Read mapping table into data table. Then loop thru that inside a using statement to read from excel directly to a data flow. That's not easy to do but it's a good option.

– KeithL
Mar 6 at 12:09





But Hadi makes a good point. I'd rather both this in c#. Read mapping table into data table. Then loop thru that inside a using statement to read from excel directly to a data flow. That's not easy to do but it's a good option.

– KeithL
Mar 6 at 12:09













@KeithL i tried to write an C# application check my answer and i am open for any suggestions

– Hadi
Mar 7 at 0:59





@KeithL i tried to write an C# application check my answer and i am open for any suggestions

– Hadi
Mar 7 at 0:59

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55009040%2fbulk-insert-from-excel-to-sql-for-selective-fields-on-the-basis-of-cell-location%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved