suga
suga

Reputation: 43

How to get data from Excel into SQL Server using Visual Studio?

I want to insert data from Excel into SQL Server. I have written code but the values are not being read from Excel:

System.Data.DataTable dt = new System.Data.DataTable();                

Workbook WB = Globals.ThisAddIn.Application.ActiveWorkbook;    
Sheets worksheets = WB.Worksheets;    
lastrow = WB.ActiveSheet.UsedRange.Rows.Count;                         

for(int i = 2; i<= lastrow; i++)      
{    
     cmd.CommandText = ("INSERT Table_1 (emp_no,emp_name,salary) values (WB.Cells[i , 1] , WB.Cells[i , 2] , WB.Cells[i , 3]))");                    
}    

Upvotes: 0

Views: 73

Answers (1)

Thomas Flinkow
Thomas Flinkow

Reputation: 5105

Strongly not recommended, but working solution:

for(int i = 2; I <= lastrow; i++)      
{    
    cmd.CommandText = ($"INSERT INTO Table_1 (emp_no,emp_name,salary) VALUES ({WB.Cells[i, 1]}, {WB.Cells[i, 2]}, {WB.Cells[i, 3]}))");                    
}    

Please don't use this and read about SQL injection for why not to use it!

Do yourself a favor and use parametrized queries instead.

Upvotes: 2

Related Questions