以下是一个简单的示例代码,用于将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/dpCu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录