将excel导入sql server数据库

本文详细介绍了在SQL Server中通过修改安全配置启用AdHocDistributedQueries组件,解决导入Excel数据时遇到的访问权限问题。包括执行SQL语句前的准备工作,如启用组件和执行配置命令,以及成功执行SQL语句后的步骤。

将excel导入sql server数据库的命令

SELECT * into 表 FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 5.0;HDR=YES;DATABASE=d:\Book1.xls',sheet1$)

表:要导入的表名

database:导入的excel文件路径

在执行sql语句过程中遇到如下提示

消息 15281,级别 16,状态 1,第 1 行
SQL Server 阻止了对组件 'Ad Hoc Distributed Queries' 的 STATEMENT'OpenRowset/OpenDatasource' 的访问,因为此组件已作为此服务器安全配置的一部分而被关闭。系统管理员可以通过使用 sp_configure 启用 'Ad Hoc Distributed Queries'。有关启用 'Ad Hoc Distributed Queries' 的详细信息,请参阅 SQL Server 联机丛书中的 "外围应用配置器"。

启用Ad Hoc Distributed Queries:
exec sp_configure 'show advanced options',1
reconfigure
exec sp_configure 'Ad Hoc Distributed Queries',1
reconfigure
使用完成后,关闭Ad Hoc Distributed Queries:
exec sp_configure 'Ad Hoc Distributed Queries',0
reconfigure
exec sp_configure 'show advanced options',0
reconfigure

再次执行sql语句,ok


### C# 实现将 Excel 文件数据导入SQL Server 数据库 为了实现这一目标,可以利用 `Microsoft.Data.SqlClient` 和 `EPPlus` 或者 `ClosedXML` 库来读取 Excel 文件并将其内容插入到 SQL Server 中。下面展示了一个完整的例子,该例子基于 ADO.NET 技术栈完成此操作。 #### 使用 EPPlus 读取 Excel 并通过 DataTable 插入到 SQL Server ```csharp using OfficeOpenXml; using Microsoft.Data.SqlClient; public void ImportExcelToSql(string excelFilePath, string connectionString) { using (var package = new ExcelPackage(new FileInfo(excelFilePath))) { var worksheet = package.Workbook.Worksheets.First(); int totalRows = worksheet.Dimension.Rows; // 创建 DataTable 来存储 Excel 的数据 DataTable dt = new DataTable(); for (int col = 1; col <= worksheet.Dimension.Columns; col++) dt.Columns.Add(worksheet.Cells[1, col].Text); for (int row = 2; row <= totalRows; row++) // 跳过标题行 { DataRow newRow = dt.NewRow(); for (int col = 1; col <= worksheet.Dimension.Columns; col++) newRow[col - 1] = worksheet.Cells[row, col].Value?.ToString() ?? ""; dt.Rows.Add(newRow); } // 将 DataTable 写入 SQL Server 表中 using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) { bulkCopy.DestinationTableName = "YourDestinationTable"; try { bulkCopy.WriteToServer(dt); } catch (Exception ex) { Console.WriteLine($"An error occurred while writing to the database: {ex.Message}"); } } } } } ``` 这段代码展示了如何使用 `Epplus` 库加载 Excel 文档,并创建一个 `DataTable` 对象填充来自 Excel 的数据[^2]。接着,使用 `SqlBulkCopy` 类高效地批量复制这些记录到指定的目标表内。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值