Solved

ExportToExcel with column names

Posted on 2007-03-22
6
242 Views
Last Modified: 2008-03-04
Is it possible to export the column names using ExportToExcel?
0
Comment
Question by:malc77
6 Comments
 
LVL 75

Assisted Solution

by:Aneesh Retnakaran
Aneesh Retnakaran earned 150 total points
ID: 18774898
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
 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 18774942
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
 
LVL 16

Expert Comment

by:rboyd56
ID: 18774970
If you are using SQL Server 2000. The Export Wizard copies the columns to the worksheet during the export.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:malc77
ID: 18775096
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
 

Author Comment

by:malc77
ID: 18793848
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
 
LVL 18

Accepted Solution

by:
Sham Haque earned 350 total points
ID: 18798596
>>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

Featured Post

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Join & Write a Comment

Having an SQL database can be a big investment for a small company. Hardware, setup and of course, the price of software all add up to a big bill that some companies may not be able to absorb.  Luckily, there is a free version SQL Express, but does …
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now