使用多个工作表和自定义 headers 将 SQL 查询导出到 excel

Export SQL query to excel with multiple worksheets and custom headers

我需要做的是,客户希望在 excel 文档中有一份报告,其中包含多个带有自定义 header 的工作表。我已经尝试过 SSRS 2008 Report Builder 2.0,但命名工作表不适用于 SSRS 2008 Report Builder 2.0。我在 SQL Server Management Studio 中尝试过 bcp,但无法将其导出到多个工作表中。我已将查询放入临时表中,有没有办法将这些查询导出到相同的 excel 文档但不同的工作表中,每个工作表具有不同的 header。

像这样

请注意每个工作表如何具有不同的名称和不同的 header。

这可能与 SQL 有关,还是有针对 SSRS 2008 Report Builder 2.0 的解决方法?

您可以使用 SQL 服务器集成服务 2008R2 (SSIS) 来执行此操作。 SSIS 有一个 Excel 数据流目标,它接受工作表名称作为参数。您可以构建自己的 SSIS 包,以这种方式填充电子表格的各种工作表。

我知道,我知道...你也遇到了错误:

Msg 15281, Level 16, State 1, Line 1
SQL Server blocked access to STATEMENT ‘OpenRowset/OpenDatasource’ of component ‘Ad Hoc Distributed Queries’ because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of ‘Ad Hoc Distributed Queries’ by using sp_configure. For more information about enabling ‘Ad Hoc Distributed Queries’, search for ‘Ad Hoc Distributed Queries’ in SQL Server Books Online.

您可以通过 T-SQL 在 SSMS 中执行此操作,请遵循 this example:

首先你需要允许SSMS绕过错误:

EXEC sp_configure 'show advanced options', 1
RECONFIGURE
EXEC sp_configure 'Ad Hoc Distributed Queries', 1
RECONFIGURE

然后您可以这样将结果保存在精确的 Excel 选项卡中:

INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;
Database=C:\Users\Zivko\Desktop\SQL Data.xlsx;','SELECT * FROM [Sheet1$]') 
SELECT * FROM dbo.DimScenario

文件 .XLSX 必须已经存在,并且选项卡具有准确的名称 [Sheet1$]