【问题标题】:Is it possible to transfer MS SQL results to a new MS Excel file?是否可以将 MS SQL 结果传输到新的 MS Excel 文件?
【发布时间】:2018-01-03 08:48:03
【问题描述】:

我正在使用以下查询将 SQL 结果传输到现有 Excel 文件。是否可以将它们转移到新的 Excel 工作表中?使用 SSIS 我们可以做到这一点,但我想知道在 SSMS 中是否有任何可能。

SP_CONFIGURE 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
GO

SP_CONFIGURE 'Database Mail XPs', 1
RECONFIGURE WITH OVERRIDE
GO

EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1   

INSERT INTO OPENROWSET 
   ('Microsoft.ACE.OLEDB.12.0', 
   'Excel 8.0;Database=E:\LessThan1300\OutofScope.xlsx;','select * from [Sheet1$]')
   select * from tboutofscope 
   where InflowDate >= CONVERT(date,getdate())

【问题讨论】:

  • 据我所知,您的查询很好。您在这里遇到任何错误吗?您的工作表在文件中是否名为 Sheet1?它是在 SQL 服务器的 E: 驱动器上还是您需要网络路径?您是否尝试使用查询创建新工作表?
  • 如果我有一个现有的工作表,这个查询可以正常工作。我想对一个新的 excel 文件做同样的事情。
  • 这是一份持续的 Excel 报告吗?您是否考虑过使用电源查询?
  • 您希望先创建新的 xlsx 文件,或者您有一个 xlsx 文件并希望将数据放在新工作表上?
  • 如果您需要一个新文件,您可以尝试使用 bcp。

标签: sql sql-server excel sql-server-2008 ssis


【解决方案1】:

您可以像这样创建模板文件的副本:

DECLARE @sqlscript VARCHAR(4000), @pathtotemplatefile VARCHAR(MAX) = 'E:\LessThan1300\template.xlsx', @pathtonewfile VARCHAR(MAX) = 'E:\LessThan1300\OutofScope.xlsx', @xlsxdatabase varchar(4000)
--SET @pathtotemplatefile = 'c:\i\1.xlsx'
--SET @pathtonewfile = 'c:\i\2.xlsx'
SET @sqlscript='copy ' + @pathtotemplatefile + ' ' + @pathtonewfile
EXECUTE master..xp_cmdshell @sqlscript, no_output

set @xlsxdatabase = 'Excel 8.0;Database=' + @pathtonewfile + ';'

INSERT INTO OPENROWSET 
   ('Microsoft.ACE.OLEDB.12.0', @xlsxdatabase,'select * from [Sheet1$]')
   select * from tboutofscope 
   where InflowDate >= CONVERT(date,getdate())

您可以根据需要动态更改新文件的名称,“创建”它,然后用预期的数据填充它。

【讨论】:

  • 谢谢。但是模板文件的内容正在复制到新文件中。我将“复制”更改为“移动”,然后删除模板并创建新文件。有什么办法可以将查询结果转储到新文件中?
  • 您应该创建一个新的空 xlsx 文件作为模板(或使用您的 OutofScope.xlsx 之一,从中删除所有行并将其命名为“OutofScope_template.xlsx”),然后使用(复制)它(到 OutofScope.xlsx )每次您需要新文件进行导出时。模板文件应保留在其位置而无需更改。
  • 我试过这个。但是模板文件的内容没有被移动。
  • 什么意思?
  • 我的意思是下面的 SQL 没有删除模板文件的内容。 INSERT INTO OPENROWSET ('Microsoft.ACE.OLEDB.12.0', 'Excel 8.0;Database=D:\POPAClause\Template.xlsx;','select * from [Sheet1$]')select top(4) * from tbLogin DECLARE @sqlscript VARCHAR(4000), @pathtotemplatefile VARCHAR(MAX) = 'D:\POPAClause\Template.xlsx', @pathtonewfile VARCHAR(MAX) = 'D:\POPAClause\T3.xlsx' SET @sqlscript='copy ' + @pathtotemplatefile + ' ' + @pathtonewfile EXECUTE master..xp_cmdshell @sqlscript, no_output
猜你喜欢
  • 2019-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多