如何使用Visual Studio将数据从Excel导入SQL Server?

时间:2021-10-31 16:21:43

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

我想将Excel中的数据插入SQL Server。我编写了代码但是没有从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]))");                    
}    

1 个解决方案

#1


1  

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!

请不要使用它并阅读SQL注入,为什么不使用它!

Do yourself a favor and use parametrized queries instead.

帮自己一个忙,然后使用参数化查询。

#1


1  

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!

请不要使用它并阅读SQL注入,为什么不使用它!

Do yourself a favor and use parametrized queries instead.

帮自己一个忙,然后使用参数化查询。