且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在c#windows窗体中将数据从Excel文件导入到sql server

更新时间:2023-02-11 08:30:33

试试这个:



http://www.c-sharpcorner.com/uploadfile/vivek4u_swamy/import-data-from-excel-to-a-sql-server-database/ [ ^ ]


您可以使用 OleDB-SQL Utility [ ^ ]。



另请参阅Excel的连接字符串和SQL查询示例。例如:

You may use the code from the OleDB-SQL Utility[^].

See also there examples of connection strings and SQL queries to Excel. For example:
SELECT NULL AS ImportID, * FROM [Sheet1






这是使用SqlBulkCopy导入的主要功能:



Here is the main function to import using SqlBulkCopy:

static void OleDbToSqlServer(string oleDbConnectionString, string oleDbSQL,
    string sqlConnectionString, string sqlTableName)
{

    oleDbConnectionString = ExpandConnectionStringFileName(oleDbConnectionString);

    OleDbConnection oleDbConnection = new OleDbConnection(oleDbConnectionString);
    try
    {
        oleDbConnection.Open();
        OleDbCommand command = new OleDbCommand(oleDbSQL, oleDbConnection);
        try
        {
            OleDbDataReader reader = command.ExecuteReader();
            try
            {
                SqlConnection sqlConnection = new SqlConnection(sqlConnectionString);
                try
                {
                    sqlConnection.Open();
                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnection))
                    {
                        bulkCopy.DestinationTableName = sqlTableName;
                        bulkCopy.WriteToServer(reader);
                    }
                }
                finally
                {
                    sqlConnection.Close();
                }
            }
            finally
            {
                reader.Close();
            }
        }
        finally
        {
            command.Dispose();
        }
    }
    finally
    {
        oleDbConnection.Close();
    }
}