简体   繁体   English

如何使用SQL存储过程将数据库表数据导出到Excel

[英]How to export database table data into excel using sql stored procedure

Suppose, I have a database Test and Table Employee where I have Id, EmpName, Salary columns. 假设我有一个数据库Test和Table Employee,其中有Id,EmpName和Salary列。 Now I need a procedure. 现在我需要一个程序。 The procedure receives one parameter: a route for saving. 该过程接收一个参数:保存路径。 In its operation, the procedure exports Excel to Employee existing tables in the database. 在操作过程中,该过程将Excel导出到数据库中的Employee现有表。 The excel file saves in the routing it received. excel文件保存在收到的路由中。

     ALTER PROCEDURE [dbo].[ExportToExcel]
    @Year int,
@ExcelFileSaveRoutePath VARCHAR(MAX) 
AS
BEGIN
    SET NOCOUNT ON 
        SET ANSI_WARNINGS OFF
        IF 1 = 0
        BEGIN
            SET FMTONLY OFF
        END
-- Here I tried many things but  cant resolve...        
SELECT * FROM [dbo].[LOAN] l
WHERE l.Submitted = 1 and  datepart(year,l.LoanDate) = @Year   

END

This is by far the best post for exporting to excel from SQL: 到目前为止,这是从SQL导出到excel的最佳文章:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926 http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926

To quote from user madhivanan, 引用用户madhivanan,

Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel 除了使用DTS和导出向导外,我们还可以使用此查询将数据从SQL Server2000导出到Excel

Create an Excel file named testing having the headers same as that of table columns and use these queries 创建一个名为test的Excel文件,其标题与表列的标题相同,并使用这些查询

1 Export data to existing EXCEL file from SQL Server table 1将数据从SQL Server表导出到现有的EXCEL文件

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;', 
    'SELECT * FROM [SheetName$]') select * from SQLServerTable

2 Export data from Excel to new SQL Server table 2将数据从Excel导出到新的SQL Server表

select * 
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [Sheet1$]')

3 Export data from Excel to existing SQL Server table (edited) 3将数据从Excel导出到现有的SQL Server表(已编辑)

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [SheetName$]')

4 If you dont want to create an EXCEL file in advance and want to export data to it, use 4如果您不想预先创建一个EXCEL文件并想将数据导出到该文件,请使用

EXEC sp_makewebtask 
    @outputfile = 'd:\testing.xls', 
    @query = 'Select * from Database_name..SQLServerTable', 
    @colheaders =1, 
    @FixedFont=0,@lastupdated=0,@resultstitle='Testing details'
(Now you can find the file with data in tabular format)

5 To export data to new EXCEL file with heading(column names), create the following procedure 5要将数据导出到带有标题(列名)的新EXCEL文件,请创建以下过程

create procedure proc_generate_excel_with_columns
(
    @db_name    varchar(100),
    @table_name varchar(100),   
    @file_name  varchar(100)
)
as

--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select 
    @columns=coalesce(@columns+',','')+column_name+' as '+column_name 
from 
    information_schema.columns
where 
    table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'

--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)

--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)

--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)

--Delete dummy file 
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)

After creating the procedure, execute it by supplying database name, table name and file path: 创建过程之后,通过提供数据库名称,表名称和文件路径来执行该过程:

EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'

Its a whom ping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it. 它平了29页,但是那是因为其他人展示了其他各种方式,以及人们像这样问问题如何做。

Follow that thread entirely and look at the various questions people have asked and how they are solved. 完全遵循该主题,并查看人们提出的各种问题以及如何解决。 I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results. 我只是略读了一些知识,并使用了其中的一些部分以获得预期的结果。

To update single cells 更新单个单元格

A member also there Peter Larson posts the following: I think one thing is missing here. 彼得·拉尔森(Peter Larson)所在的成员也发表了以下文章:我认为这里缺少一件事。 It is great to be able to Export and Import to Excel files, but how about updating single cells? 能够导出和导入到Excel文件很棒,但是如何更新单个单元格呢? Or a range of cells? 还是一系列细胞?

This is the principle of how you do manage that 这是您如何管理的原则

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99

You can also add formulas to Excel using this: 您还可以使用以下方法将公式添加到Excel:

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'

Exporting with column names using T-SQL 使用T-SQL导出列名称

Member Mladen Prajdic also has a blog entry on how to do this here 成员Mladen Prajdic也在此处提供了有关如何执行此操作的博客条目

References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). 参考:www.sqlteam.com(顺便说一下,对于希望从SQL Server中获得更多收益的人来说,这是一个出色的博客/论坛)。 For error referencing I used this 对于错误引用,我使用了这个

Errors that may occur If you get the following error: 如果出现以下错误,可能会发生的错误:

OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries OLE DB提供程序'Microsoft.Jet.OLEDB.4.0'不能用于分布式查询

Then run this: 然后运行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用存储过程从 SQL 服务器数据库中提取数据 - How to pull data from SQL Server database using a stored procedure 从存储过程导出到Excel - SQL被阻止 - Export to Excel from stored procedure - SQL blocked 使用存储过程将SQL表/数据导出到MS Access - Export SQL Tables/Data to MS Access using stored procedure 如何将SQL表数据导出到Excel工作表中? - how to export sql table data into excel worksheet? 如何使用表数据调用存储过程? - how to call a stored procedure using table data? 如何在T-SQL存储过程中访问另一个数据库中的表 - How to access table in another database in T-SQL stored procedure 如何使用存储过程将datetime插入SQL Server数据库表中? - How to insert datetime into a SQL Server database table with a stored procedure? 如何使用存储过程在sql server中检查上一周的数据与SQL表 - how to check SQL table with last one week data in sql server using stored procedure 在 SQL Server 2008 中使用 xml 和存储过程将数据插入到表中 - Insert data in to table using xml and stored procedure in SQL Server 2008 如何使用返回json的存储过程调用Web服务并使用sql server将数据存储在表中? - how to Call web service using stored procedure which returns json and store data in table using sql server?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM