Sometimes you find these really old files floating around on your
harddrive and you forget that you ever downloaded them. Here is one
such example. I have no idea where I got this or who to credit for its
creation, but I've had it for awhile and came across it and thought it
would be something nice to share with you, as Iâm sure it is something
of great help to many of you. This
is a T-SQL script that uses the system stored procedures sp_OA* for
creating and handling OLE objects, ADO, Jet and a linked server to
create and
populate an XLS file from a select statement. By default, if the
XLS file already exists, the result of the query will get appended to
the worksheet. You'll have to add some code to check for and
delete the file before creating if that is your desired behavior.
Oh, and I used this a long time ago
with some minor code changes and it worked fine, but this is the
original script using the pubs database, so there are changes youâll
have to make, and they should be fairly obvious to you.
Create and Excel spreadsheet via 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