C# 代码示例:将 Excel 数据导入 SQL Server 数据库
以下是一个简单的示例代码,用于将 Excel 文件中的数据导入到 SQL Server 数据库中。请注意,此代码可能需要根据您的具体情况进行修改,包括 Excel 文件和数据库表的名称,以及数据库连接字符串的设置。
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelToSqlServer
{
class Program
{
static void Main(string[] args)
{
// Excel 文件路径
string excelFilePath = 'C:\data\sample.xlsx';
// 数据库连接字符串
string connectionString = 'Data Source=SERVER;Initial Catalog=DATABASE;Integrated Security=True';
// Excel 文件中的工作表名称
string sheetName = 'Sheet1';
// 数据库表名称
string tableName = 'SampleTable';
// 打开 Excel 文件
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Open(excelFilePath);
Excel.Worksheet sheet = workbook.Sheets[sheetName];
// 获取 Excel 文件中的数据范围
Excel.Range range = sheet.UsedRange;
// 创建数据库连接对象
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 打开数据库连接
connection.Open();
// 创建 SQL 语句
string sql = 'INSERT INTO ' + tableName + ' VALUES (@Field1, @Field2, @Field3)';
// 创建 SQL 命令对象
SqlCommand command = new SqlCommand(sql, connection);
// 遍历 Excel 文件中的每一行数据
for (int row = 2; row <= range.Rows.Count; row++)
{
// 设置 SQL 参数值
command.Parameters.AddWithValue('@Field1', range.Cells[row, 1].Value2);
command.Parameters.AddWithValue('@Field2', range.Cells[row, 2].Value2);
command.Parameters.AddWithValue('@Field3', range.Cells[row, 3].Value2);
// 执行 SQL 命令
command.ExecuteNonQuery();
// 清除 SQL 参数
command.Parameters.Clear();
}
}
// 关闭 Excel 文件
workbook.Close(false, Missing.Value, Missing.Value);
excel.Quit();
Marshal.ReleaseComObject(sheet);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(excel);
}
}
}
原文地址: https://www.cveoy.top/t/topic/nES3 著作权归作者所有。请勿转载和采集!