SQL导出数据到EXCEL文件

原创 2004年09月25日 16:26:00

Create Excel XLS from T-SQL
---------------------------------------------------------------------------
-- Create XLS script DAL - 04/24/2003
--
-- Designed for Agent scheduling, turn on "Append output for step history"
--
-- Search for %%% to find adjustable constants and other options
--
-- Uses OLE for ADO and OLE DB to create the XLS file if it does not exist
--   Linked server requires the XLS to exist before creation
-- Uses OLE ADO to Create the XLS Worksheet for use as a table by T-SQL
-- Uses Linked Server to allow T-SQL access to XLS table
-- Uses T-SQL to populate te XLS worksheet, very fast
--
PRINT 'Begin CreateXLS script at '+RTRIM(CONVERT(varchar(24),GETDATE(),121))+' '
PRINT ''
GO

SET NOCOUNT ON
DECLARE @Conn int -- ADO Connection object to create XLS
 , @hr int -- OLE return value
 , @src varchar(255) -- OLE Error Source
 , @desc varchar(255) -- OLE Error Description
 , @Path varchar(255) -- Drive or UNC path for XLS
 , @Connect varchar(255) -- OLE DB Connection string for Jet 4 Excel ISAM
 , @WKS_Created bit -- Whether the XLS Worksheet exists
 , @WKS_Name varchar(128) -- Name of the XLS Worksheet (table)
 , @ServerName nvarchar(128) -- Linked Server name for XLS
 , @DDL varchar(8000) -- Jet4 DDL for the XLS WKS table creation
 , @SQL varchar(8000) -- INSERT INTO XLS T-SQL
 , @Recs int -- Number of records added to XLS
 , @Log bit -- Whether to log process detail

-- Init variables
SELECT @Recs = 0
 -- %%% 1 = Verbose output detail, helps find problems, 0 = minimal output detail
 , @Log = 1
-- %%% assign the UNC or path and name for the XLS file, requires Read/Write access
--   must be accessable from server via SQL Server service account
--   & SQL Server Agent service account, if scheduled
SET @Path = 'C:/TEMP/Test_'+CONVERT(varchar(10),GETDATE(),112)+'.xls'
-- assign the ADO connection string for the XLS creation
SET @Connect = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source='+@Path+';Extended Properties=Excel 8.0'
-- %%% assign the Linked Server name for the XLS population
SET @ServerName = 'EXCEL_TEST'
-- %%% Rename Table as required, this will also be the XLS Worksheet name
SET @WKS_Name = 'People'
-- %%% Table creation DDL, uses Jet4 syntax,
--   Text data type = varchar(255) when accessed from T-SQL
SET @DDL = 'CREATE TABLE '+@WKS_Name+' (SSN Text, Name Text, Phone Text)'
-- %%% T-SQL for table population, note the 4 part naming required by Jet4 OLE DB
--   INSERT INTO SELECT, INSERT INTO VALUES, and EXEC sp types are supported
--   Linked Server does not support SELECT INTO types
SET @SQL = 'INSERT INTO '+@ServerName+'...'+@WKS_Name+' (SSN, Name, Phone) '
SET @SQL = @SQL+'SELECT au_id AS SSN'
SET @SQL = @SQL+', LTRIM(RTRIM(ISNULL(au_fname,'''')+'' ''+ISNULL(au_lname,''''))) AS Name'
SET @SQL = @SQL+', phone AS Phone '
SET @SQL = @SQL+'FROM pubs.dbo.authors'

IF @Log = 1 PRINT 'Created OLE ADODB.Connection object'
-- Create the Conn object
EXEC @hr = sp_OACreate 'ADODB.Connection', @Conn OUT
IF @hr <> 0 -- have to use <> as OLE / ADO can return negative error numbers
BEGIN
 -- Return OLE error
 EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT
 SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc
 RETURN
END

IF @Log = 1 PRINT char(9)+'Assigned ConnectionString property'
-- Set a the Conn object's ConnectionString property
--   Work-around for error using a variable parameter on the Open method
EXEC @hr = sp_OASetProperty @Conn, 'ConnectionString', @Connect
IF @hr <> 0
BEGIN
 -- Return OLE error
 EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT
 SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc
 RETURN
END

IF @Log = 1 PRINT char(9)+'Open Connection to XLS, for file Create or Append'
-- Call the Open method to create the XLS if it does not exist, can't use parameters
EXEC @hr = sp_OAMethod @Conn, 'Open'
IF @hr <> 0
BEGIN
 -- Return OLE error
 EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT
 SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc
 RETURN
END

-- %%% This section could be repeated for multiple Worksheets (Tables)
IF @Log = 1 PRINT char(9)+'Execute DDL to create '''+@WKS_Name+''' worksheet'
-- Call the Execute method to Create the work sheet with the @WKS_Name caption,
--   which is also used as a Table reference in T-SQL
-- Neat way to define column data types in Excel worksheet
--   Sometimes converting to text is the only work-around for Excel's General
--   Cell formatting, even though the Cell contains Text, Excel tries to format
--   it in a "Smart" way, I have even had to use the single quote appended as the
--   1st character in T-SQL to force Excel to leave it alone
EXEC @hr = sp_OAMethod @Conn, 'Execute', NULL, @DDL, NULL, 129 -- adCmdText + adExecuteNoRecords
-- 0x80040E14 for table exists in ADO
IF @hr = 0x80040E14
 -- kludge, skip 0x80042732 for ADO Optional parameters (NULL) in SQL7
 OR @hr = 0x80042732
BEGIN
 -- Trap these OLE Errors
 IF @hr = 0x80040E14
 BEGIN
  PRINT char(9)+''''+@WKS_Name+''' Worksheet exists for append'
  SET @WKS_Created = 0
 END
 SET @hr = 0 -- ignore these errors
END
IF @hr <> 0
BEGIN
 -- Return OLE error
 EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT
 SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc
 RETURN
END

IF @Log = 1 PRINT 'Destroyed OLE ADODB.Connection object'
-- Destroy the Conn object, +++ important to not leak memory +++
EXEC @hr = sp_OADestroy @Conn
IF @hr <> 0
BEGIN
 -- Return OLE error
 EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT
 SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc
 RETURN
END

-- Linked Server allows T-SQL to access the XLS worksheet (Table)
--   This must be performed after the ADO stuff as the XLS must exist
--   and contain the schema for the table, or worksheet
IF NOT EXISTS(SELECT srvname from master.dbo.sysservers where srvname = @ServerName)
BEGIN
 IF @Log = 1 PRINT 'Created Linked Server '''+@ServerName+''' and Login'
 EXEC sp_addlinkedserver @server = @ServerName
      , @srvproduct = 'Microsoft Excel Workbook'
      , @provider = 'Microsoft.Jet.OLEDB.4.0'
      , @datasrc = @Path
      , @provstr = 'Excel 8.0'
 -- no login name or password are required to connect to the Jet4 ISAM linked server
 EXEC sp_addlinkedsrvlogin @ServerName, 'false'
END

-- Have to EXEC the SQL, otherwise the SQL is evaluated
--   for the linked server before it exists
EXEC (@SQL)
PRINT char(9)+'Populated '''+@WKS_Name+''' table with '+CONVERT(varchar,@@ROWCOUNT)+' Rows'

-- %%% Optional you may leave the Linked Server for other XLS operations
--   Remember that the Linked Server will not create the XLS, so remove it
--   When you are done with it, especially if you delete or move the file
IF EXISTS(SELECT srvname from master.dbo.sysservers where srvname = @ServerName)
BEGIN
 IF @Log = 1 PRINT 'Deleted Linked Server '''+@ServerName+''' and Login'
 EXEC sp_dropserver @ServerName, 'droplogins'
END
GO

SET NOCOUNT OFF
PRINT ''
PRINT 'Finished CreateXLS script at '+RTRIM(CONVERT(varchar(24),GETDATE(),121))+' '
GO

目的
SET @Path = 'C:/TEMP/Test_'+CONVERT(varchar(10),GETDATE(),112)+'.xls'


SET @SQL = 'INSERT INTO '+@ServerName+'...'+@WKS_Name+' (SSN, Name, Phone) '
SET @SQL = @SQL+'SELECT au_id AS SSN'
SET @SQL = @SQL+', LTRIM(RTRIM(ISNULL(au_fname,'''')+'' ''+ISNULL(au_lname,''''))) AS Name'
SET @SQL = @SQL+', phone AS Phone '
SET @SQL = @SQL+'FROM pubs.dbo.authors'

[Qt]导入导出Excel

Qt对Excel的导入导出,有备无患 void onImportExcel(QString filePath) { QAxObject excel("Excel.Applicatio...
  • luols
  • luols
  • 2015年09月28日 10:03
  • 6175

C#导出数据表为Excel文件

博文以导出Access数据库中的数据表为例,只要修改一下同样可以用于SQL Server数据库。 string filePath = "F:\\Book.xls"; string OleDbConn...
  • softimite_zifeng
  • softimite_zifeng
  • 2017年01月10日 17:46
  • 229

PHP导出数据到Excel

PHP导出数据到Excel在Web开发中经常需要将一些数据导入到Excel表格中,比如需要导出符合条件的用户数据,导出项包括姓名、性别、身份证号、联系方式等等。那么问题来了,在导出的数据中如果出现比较...
  • u012162220
  • u012162220
  • 2015年03月21日 20:57
  • 809

Sybase数据库大量数据导出Excel

应客户要求,导出数据库中的数据为Excel,只在一个Sheet中,Excel中的内容要与数据库里的内容一致(主要针对日期型数据)。             由于之前接触过POI,对POI的一些特性还是...
  • shanhuijava
  • shanhuijava
  • 2013年09月17日 14:34
  • 1888

C#导出数据到Excel文件

///         /// 导出GridView的数据到Excel的方法--没有用服务器模式加载数据的使用         ///         /// 要导出数据的GridView ...
  • xiaoyu812289718
  • xiaoyu812289718
  • 2014年04月29日 11:11
  • 1050

Java中导出数据到Excel处理方法

在开发中我们经常遇到把数据导出到Excel中的需求,这里简单的描述下个人实现方式,提供了Excel2003 与Excel2007两种实现方式。实现如下:   1、接口类demo: packag...
  • baijianjun123456
  • baijianjun123456
  • 2016年04月01日 11:01
  • 2832

sql server2008 导出表到excel及 导入(压测大数据)

excel文件导入sql sever中: 如果就把Excel数据插入一个新表,就选择【复制一个或多个表或视图的数据】  如果想把Excel数据插入到已存在的一张表中,则选择下面的【编写查询以指定要传...
  • u010479690
  • u010479690
  • 2013年12月25日 14:19
  • 1048

VC++程序导出数据到EXCEL

VC程序导出数据到EXCEL   VC导出数据到EXCEL 收藏 我们制作应用软件的时候,经常要把结果以报表的形式输出,当前使用较为广泛的当然是Excel表格,本文简略介绍在VC++...
  • bbdxf
  • bbdxf
  • 2013年04月02日 20:17
  • 3845

phpexcel导出数据库数据生成excel文件

由于项目的需要把数据库的数据导出生成excel文件,发了点时间学习里下PHPexcel导出excel文档 1.查询服务器数据库,数据库查询返回json格式数据。 2.json数据转换为数组,生成的数组...
  • cwcwj3069
  • cwcwj3069
  • 2015年05月06日 11:08
  • 4133

【代码实现】PHP导入Excel和导出数据为Excel文件

文章来源:PHP开发学习门户 地址:http://www.phpthinking.com/archives/560 有时需要将Excel表格的数据导入到mysql数据库中,我们使用PHP的...
  • Ksly_Tkol
  • Ksly_Tkol
  • 2014年10月10日 09:25
  • 2747
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:SQL导出数据到EXCEL文件
举报原因:
原因补充:

(最多只允许输入30个字)