c#winform导入excel数据并存储到SQL Server数据库中
时间: 2024-01-15 11:05:07 浏览: 332
以下是C# WinForm中将Excel数据导入到SQL Server数据库中的步骤:
1. 需要添加对Microsoft.Office.Interop.Excel和System.Data.SqlClient的引用。
2. 建立一个Windows Form应用程序,并在表单上添加一个按钮,用于触发导入Excel数据的过程。
3. 在按钮的Click事件中编写代码,打开Excel文件并读取数据。
```csharp
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Open(@"C:\example.xlsx");
Excel.Worksheet worksheet = workbook.Sheets[1];
int rowsCount = worksheet.UsedRange.Rows.Count;
int columnsCount = worksheet.UsedRange.Columns.Count;
for (int row = 1; row <= rowsCount; row++)
{
for (int col = 1; col <= columnsCount; col++)
{
string cellValue = (worksheet.Cells[row, col] as Excel.Range).Value.ToString();
// Do something with the cell value
}
}
workbook.Close();
excelApp.Quit();
```
4. 创建一个SqlConnection对象,用于连接到SQL Server数据库。
```csharp
using System.Data.SqlClient;
SqlConnection connection = new SqlConnection("Data Source=serverName;Initial Catalog=databaseName;Integrated Security=True");
connection.Open();
```
5. 创建一个SqlCommand对象,用于执行插入语句。
```csharp
SqlCommand command = new SqlCommand("INSERT INTO TableName (Column1, Column2) VALUES (@Value1, @Value2)", connection);
command.Parameters.AddWithValue("@Value1", cellValue1);
command.Parameters.AddWithValue("@Value2", cellValue2);
command.ExecuteNonQuery();
```
6. 在循环中使用SqlCommand对象插入数据。
7. 关闭SqlConnection对象。
```csharp
connection.Close();
```
完成以上步骤后,您的C# WinForm应用程序就能够将Excel数据导入到SQL Server数据库中了。
阅读全文
相关推荐















