且构网

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

使用 C# 将 Excel 文件导入 Microsoft SQL Server

更新时间:2023-01-21 13:28:30

string excelConnectionString = @"Provider=Microsoft 
.Jet.OLEDB.4.0;Data Source=Book1.xls;Extended 
Properties=""Excel 8.0;HDR=YES;"""; 

//创建到 Excel 工作簿的连接

我们可以像这样将excel导入sql server

We can Import excel to sql server like this

使用(OleDbConnection 连接 =新的 OleDbConnection(excelConnectionString)){

OleDbCommand 命令 = 新的 OleDbCommand("Select ID,Data FROM [Data$]", 连接);

connection.Open(); 


`// Create DbDataReader to Data Worksheet `
using (DbDataReader dr = command.ExecuteReader()) 
{ 
    // SQL Server Connection String 
    string sqlConnectionString = "Data Source=.; 
       Initial Catalog=Test;Integrated Security=True"; 


    // Bulk Copy to SQL Server 
    using (SqlBulkCopy bulkCopy = 
               new SqlBulkCopy(sqlConnectionString)) 
    { 
        bulkCopy.DestinationTableName = "ExcelData"; 
        bulkCopy.WriteToServer(dr); 
    }