ExportToExcel with column names

Is it possible to export the column names using ExportToExcel?
malc77Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Aneesh RetnakaranDatabase AdministratorCommented:
use some thing like this


SELECT 'ColumnName1', 'ColumnName2'   ------Note:  the column names are enclosed within Quotes
UNION ALL

SELECT ColumnName1, ColumnName2   --- Note : here is the actual statement
FROM tableName


Now you can save this to excel
0
Aneesh RetnakaranDatabase AdministratorCommented:
if you are using Sql 2005, you can actually export the data with the column names

SQL Server managemen Studion -> options -> Query results -> SQL Server -> Results To grid -  make sure that you can checked "Include column headers ..."
0
rboyd56Commented:
If you are using SQL Server 2000. The Export Wizard copies the columns to the worksheet during the export.
0
Newly released Acronis True Image 2019

In announcing the release of the 15th Anniversary Edition of Acronis True Image 2019, the company revealed that its artificial intelligence-based anti-ransomware technology – stopped more than 200,000 ransomware attacks on 150,000 customers last year.

malc77Author Commented:
Greetings aneeshattingal:

I am getting the following Error:

Msg 103, Level 15, State 4, Line 1
The identifier that starts with 'SELECT 'Nokia P/N','Description','Models','Tessco','U4','U1','PrcSrc','Category','SrvcLvL','Region','SpcHndlng','Ca' is too long. Maximum length is 128.

My code is:
EXEC ExportToExcel '1USD01321','sa','MRP',"SELECT 'NokiaP/N','Description','Models','Tessco','U4','U1','PrcSrc','Category','SrvcLvL','Region','SpcHndlng','CaseMultiples','MOQ','InitBuyQty','RptDte'
Union All
Select [Nokia P/N],Description,Models,Tessco,U4,U1,PrcSrc,Category,SrvcLvL,Region,
SpcHndlng,CaseMultiples,MOQ,InitBuyQty,RptDte FROM MRPDev.dbo.TesscoAddsRpt",'D:\ImportToExcel.xls'

Is there any way to lengthen this?
0
malc77Author Commented:
Greetings Experts,

I could use a bit more help with this particular question.  Please review the attached code and result.  Can this be solved?

This Works!!!!
StoreProcedure Call:
Set QUOTED_IDENTIFIER OFF
EXEC ExportToExcel 'Server','sa','password',"SELECT 'Nokia P/N','Description','Models'
Union All
Select [Nokia P/N],Description,Models FROM MRPDev.dbo.TesscoAddsRpt",'D:\ImportToExcel.xls'


But as I add more columns I get the following error:
sp call:
Set QUOTED_IDENTIFIER OFF
EXEC ExportToExcel 'Server','sa','password',"SELECT 'Nokia P/N','Description','Models','Tessco'
Union All
Select [Nokia P/N],Description,Models,Tessco FROM MRPDev.dbo.TesscoAddsRpt",'D:\ImportToExcel.xls'

Error:
Msg 245, Level 16, State 1, Procedure ExportToExcel, Line 72
Conversion failed when converting the varchar value 'error with method ExecuteWithResults ' to data type int.


StoredProcedure:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER OFF
GO

ALTER PROCEDURE [dbo].[ExportToExcel] (
  @server sysname = null,
  @uname sysname = null,
  @pwd sysname = null,
  @QueryText nvarchar(1000) = null,
  @filename nvarchar(1000) = 'D:\ImportToExcel.xls'
)
AS
DECLARE @SQLServer int,
        @QueryResults int,
        @CurrentResultSet int,
        @object int,
        @WorkBooks int,
        @WorkBook int,
        @Range int,
        @hr int,
        @Columns int,
        @Rows int,
        @indColumn int,
        @indRow int,
        @off_Column int,
        @off_Row int,
        @code_str nvarchar(1000),
        @result_str nvarchar(1000)

IF @QueryText IS NULL
  BEGIN
    PRINT 'Set the query string'
    RETURN
  END

-- Sets the server to the local server
IF @server IS NULL SELECT @server = @@servername

-- Sets the username to the current user name
IF @uname IS NULL SELECT @uname = SYSTEM_USER

SET NOCOUNT ON

EXEC @hr = sp_OACreate 'SQLDMO.SQLServer', @SQLServer OUT
IF @hr <> 0
BEGIN
    PRINT 'error create SQLDMO.SQLServer'
    RETURN
END

--  Connect to the SQL Server
IF @pwd IS NULL
  BEGIN
    EXEC @hr = sp_OAMethod @SQLServer, 'Connect', null, @server, @uname
    IF @hr <> 0
       BEGIN
         PRINT 'error Connect'
         RETURN
       END
  END
ELSE
  BEGIN
    EXEC @hr = sp_OAMethod @SQLServer, 'Connect', null, @server, @uname, @pwd
    IF @hr <> 0
      BEGIN
        PRINT 'error Connect'
        RETURN
      END
  END

SELECT @result_str = 'ExecuteWithResults("' + @QueryText + '")'
EXEC @hr = sp_OAMethod @SQLServer, @result_str, @QueryResults OUT
IF @hr <> 0
BEGIN
    PRINT 'error with method ExecuteWithResults ' + @QueryResults
    RETURN
END

EXEC @hr = sp_OAMethod @QueryResults, 'CurrentResultSet', @CurrentResultSet OUT
IF @hr <> 0
BEGIN
    PRINT 'error get CurrentResultSet'
    RETURN
END

EXEC @hr = sp_OAMethod @QueryResults, 'Columns', @Columns OUT
IF @hr <> 0
BEGIN
    PRINT 'error get Columns'
    RETURN
END

EXEC @hr = sp_OAMethod @QueryResults, 'Rows', @Rows OUT
IF @hr <> 0
BEGIN
    PRINT 'error get Rows'
    RETURN
END

EXEC @hr = sp_OACreate 'Excel.Application', @object OUT
IF @hr <> 0
BEGIN
    PRINT 'error create Excel.Application'
    RETURN
END

EXEC @hr = sp_OAGetProperty @object, 'WorkBooks', @WorkBooks OUT
IF @hr <> 0
BEGIN
    PRINT 'error create WorkBooks'
    RETURN
END

EXEC @hr = sp_OAGetProperty @WorkBooks, 'Add', @WorkBook OUT
IF @hr <> 0
BEGIN
    PRINT 'error with method Add'
    RETURN
END

EXEC @hr = sp_OAGetProperty @object, 'Range("A1")', @Range OUT
IF @hr <> 0
BEGIN
    PRINT 'error create Range'
    RETURN
END

SELECT @indRow = 1
SELECT @off_Row = 0
SELECT @off_Column = 1

WHILE (@indRow <= @Rows)
BEGIN
SELECT @indColumn = 1

WHILE (@indColumn <= @Columns)
BEGIN

EXEC @hr = sp_OAMethod @QueryResults, 'GetColumnString', @result_str OUT, @indRow, @indColumn
IF @hr <> 0
BEGIN
    PRINT 'error get GetColumnString'
    RETURN
END

EXEC @hr = sp_OASetProperty @Range, 'Value', @result_str
IF @hr <> 0
BEGIN
    PRINT 'error set Value'
    RETURN
END

EXEC @hr = sp_OAGetProperty @Range, 'Offset', @Range OUT, @off_Row, @off_Column
IF @hr <> 0
BEGIN
    PRINT 'error get Offset'
    RETURN
END

SELECT @indColumn = @indColumn + 1

END

SELECT @indRow = @indRow + 1
SELECT @code_str = 'Range("A' + LTRIM(str(@indRow)) + '")'
EXEC @hr = sp_OAGetProperty @object, @code_str, @Range OUT
IF @hr <> 0
BEGIN
    PRINT 'error create Range'
    RETURN
END

END

SELECT @result_str = 'exec master..xp_cmdshell ''del ' + @filename + ''', no_output'
EXEC(@result_str)
SELECT @result_str = 'SaveAs("' + @filename + '")'
EXEC @hr = sp_OAMethod @WorkBook, @result_str
IF @hr <> 0
BEGIN
    PRINT 'error with method SaveAs'
    RETURN
END

EXEC @hr = sp_OAMethod @WorkBook, 'Close'
IF @hr <> 0
BEGIN
    PRINT 'error with method Close'
    RETURN
END

EXEC @hr = sp_OADestroy @object
IF @hr <> 0
BEGIN
    PRINT 'error destroy Excel.Application'
    RETURN
END

EXEC @hr = sp_OADestroy @SQLServer
IF @hr <> 0
BEGIN
    PRINT 'error destroy SQLDMO.SQLServer'
    RETURN
END
0
Sham HaqueSenior SAP CRM ConsultantCommented:
>>But as I add more columns I get the following error:
sp call:
Set QUOTED_IDENTIFIER OFF
EXEC ExportToExcel 'Server','sa','password',"SELECT 'Nokia P/N','Description','Models','Tessco'
Union All
Select [Nokia P/N],Description,Models,Tessco FROM MRPDev.dbo.TesscoAddsRpt",'D:\ImportToExcel.xls'

Error:
Msg 245, Level 16, State 1, Procedure ExportToExcel, Line 72
Conversion failed when converting the varchar value 'error with method ExecuteWithResults ' to data type int.


The error is because a UNION query requires that each SELECT contains the same number of columns (ok there) with the same data types (this is your problem).
You should convert all the items in your second SELECT to varchar, which will solve your problem of exprting the data. Not sure how this will affect the resulting file tho....


Set QUOTED_IDENTIFIER OFF
EXEC ExportToExcel 'Server','sa','password',"SELECT 'Nokia P/N','Description','Models','Tessco'
Union All
Select CONVERT(VARCHAR(255),[Nokia P/N]),CONVERT(VARCHAR(255),Description),CONVERT(VARCHAR(255),Models),CONVERT(VARCHAR(255),Tessco) FROM MRPDev.dbo.TesscoAddsRpt",'D:\ImportToExcel.xls'
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2005

From novice to tech pro — start learning today.