Export to Excel Stored Procedure Fails

Greetiings Experts,

I am using SQLServer 2005.  My stored procedure writes data from a table to an Excel spreadsheet.  It works fine for rows 1-14, however an error occurs whenever the table has more the 14 rows of data.  I realize this is alot to step thru on my behalf, however, your help and prompt response is deeply appreciated.

Code That Works:
Use database
Set QUOTED_IDENTIFIER OFF
EXEC ExportToExcel 'servername','userid','password',"SELECT top 14 'Nokia P/N',
'Description','Models','Tessco','U1','U4','PrcSrc','Category','SrvcLvL','Region','SpclHndlng','CaseMultiples',
'MOQ','InitBuyQty','RptDte'
Union All
Select      top 14 convert(varchar(255),[Nokia P/N]),convert(varchar(255),Description),
      convert(varchar(255),Models),convert(varchar(255),Tessco),convert(varchar(255),U1),
      convert(varchar(255),U4),convert(varchar(255),PrcSrc),convert(varchar(255),Category),
      convert(varchar(255),SrvcLvL),convert(varchar(255),Region),
                      convert(varchar(255),SpclHndlng), convert(varchar(255),CaseMultiples),
                      convert(varchar(255),MOQ),convert(varchar(255),InitBuyQty),
                      convert(varchar(11),RptDte,120)                              FROM MRPDev.dbo.TesscoAddsRpt",'C:\Inetpub\wwwroot\Uploads\TesscoAdds.xls'


This Fails:
Use database
Set QUOTED_IDENTIFIER OFF
EXEC ExportToExcel 'servername','userid','password',"SELECT 'Nokia P/N',
'Description','Models','Tessco','U1','U4','PrcSrc','Category','SrvcLvL','Region','SpclHndlng','CaseMultiples',
'MOQ','InitBuyQty','RptDte'
Union All
Select      convert(varchar(255),[Nokia P/N]),convert(varchar(255),Description),
      convert(varchar(255),Models),convert(varchar(255),Tessco),convert(varchar(255),U1),
      convert(varchar(255),U4),convert(varchar(255),PrcSrc),convert(varchar(255),Category),
      convert(varchar(255),SrvcLvL),convert(varchar(255),Region),
                      convert(varchar(255),SpclHndlng), convert(varchar(255),CaseMultiples),
                      convert(varchar(255),MOQ),convert(varchar(255),InitBuyQty),
                      convert(varchar(11),RptDte,120)                              FROM MRPDev.dbo.TesscoAddsRpt",'C:\Inetpub\wwwroot\Uploads\TesscoAdds.xls'

Error:
'error get Offset'


Code:
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) = 'C:\Inetpub\wwwroot\Uploads\TesscoAdds.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
--Print @QueryResults
--Print @result_str
--Print @indRow
--Print @indColumn
IF @hr <> 0
BEGIN
    PRINT 'error get GetColumnString'
    RETURN
END

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


EXEC @hr = sp_OAGetProperty @Range, 'Offset', @Range OUT, @off_Row, @off_Column
--Print @hr
--Print @Range
--Print @off_Row
--Print @off_Column
--exec sp_OAGetErrorInfo @Range
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
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.

LowfatspreadCommented:
not at all clear what your trying to do here...

however

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

rewrite as
EXEC @hr = sp_OAGetProperty @Range, 'Offset', @Range OUT, @off_Row, @off_Column
--exec sp_OAGetErrorInfo @Range
IF @hr <> 0
BEGIN
    PRINT 'error get Offset'
   Print @hr
 Print @Range
Print @off_Row
 Print @off_Column
    RETURN
END

and tell us what the values are...

also you specify @Range twice on the call is that intended?  especially as your trying to overwrite it ,.,,
I'd always declare another variable and swap it in if thats required on successfult completeion
that way you can always see the in and out conditions..
0
malc77Author Commented:
Greetings LowFatSpread,
Your response is greatly appreciated.  I am a novice attempting to use borrowed code. So I can't explain why the range is called twice...my apologies.....Please find the results below:

error get Offset
10077
-65794
0
1

0
LowfatspreadCommented:
can you add these stored procs

IF EXISTS(SELECT name FROM sys.objects
          WHERE name = N'HexToChar')
    DROP PROCEDURE HexToChar;
GO
CREATE PROCEDURE HexToChar
    @BinValue varbinary(255),
    @HexCharValue nvarchar(255) OUTPUT
AS
    DECLARE @CharValue nvarchar(255);
    DECLARE @Position int;
    DECLARE @Length int;
    DECLARE @HexString nchar(16);
    SELECT @CharValue = N'0x';
    SELECT @Position = 1;
    SELECT @Length = DATALENGTH(@BinValue);
    SELECT @HexString = N'0123456789ABCDEF';
    WHILE (@Position <= @Length)
    BEGIN
        DECLARE @TempInt int;
        DECLARE @FirstInt int;
        DECLARE @SecondInt int;
        SELECT @TempInt = CONVERT(int, SUBSTRING(@BinValue,@Position,1));
        SELECT @FirstInt = FLOOR(@TempInt/16);
        SELECT @SecondInt = @TempInt - (@FirstInt*16);
        SELECT @CharValue = @CharValue +
            SUBSTRING(@HexString, @FirstInt+1, 1) +
            SUBSTRING(@HexString, @SecondInt+1, 1);
        SELECT @Position = @Position + 1;
    END
    SELECT @HexCharValue = @CharValue;
GO

CREATE PROCEDURE DisplayOAErrorInfo
    @Object int,
    @HResult int
AS
    DECLARE @Output nvarchar(255);
    DECLARE @HRHex nchar(10);
    DECLARE @HR int;
    DECLARE @Source nvarchar(255);
    DECLARE @Description nvarchar(255);
    PRINT N'OLE Automation Error Information';
    EXEC HexToChar @HResult, @HRHex OUT;
    SELECT @Output = N'  HRESULT: ' + @HRHex;
    PRINT @Output;
    EXEC @HR = sp_OAGetErrorInfo
        @Object,
        @Source OUT,
        @Description OUT;
    IF @HR = 0
    BEGIN
        SELECT @Output = N'  Source: ' + @Source;
        PRINT @Output;
        SELECT @Output = N'  Description: '
               + @Description;
        PRINT @Output;
    END
    ELSE
    BEGIN
       PRINT N' sp_OAGetErrorInfo failed.';
       RETURN;
    END
GO
 

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

as

EXEC @hr = sp_OAGetProperty @Range, 'Offset', @Range OUT, @off_Row, @off_Column
--exec sp_OAGetErrorInfo @Range
IF @hr <> 0
BEGIN
    PRINT 'error get Offset Indcolumn=' + convert(varchar(10),@indcolumn)
exec DisplayOAErrorInfo,@range,@hr
   Print @hr
 Print @Range
Print @off_Row
 Print @off_Column
    RETURN
END


0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

malc77Author Commented:
I added the new procedures and edited your code a bit because I was getting a error near ','  Is this correct?   I am now getting an ' error create Excel.Application'

EXEC @hr = sp_OAGetProperty @Range, 'Offset', @Range OUT, @off_Row, @off_Column
IF @hr <> 0
BEGIN
    PRINT 'error get Offset Indcolumn=' + convert(varchar(10),@indcolumn)
exec DisplayOAErrorInfo   <-removed the comma from here-->  @range, @hr
   Print @hr
 Print @Range
Print @off_Row
 Print @off_Column
    RETURN
END
0
LowfatspreadCommented:
sorry
exec DisplayOAErrorInfo @range,@hr
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
malc77Author Commented:
Ok....I am getting the following results:

error get Offset Indcolumn=11
OLE Automation Error Information

  HRESULT: 0x0000275D
  Source: ODSOLE Extended Procedure
 
10077
-65794
0
1
0
LowfatspreadCommented:
have you examined the data to see what is different in either column 11 or the 11 row in the output of the 2 queries?
0
malc77Author Commented:
Checking......
0
malc77Author Commented:
Greetings Expert,

Sorry for the delay....I was pulled to another project....I am still having trouble and would appreciate your help.....I have checked the data and all is in good order...please see sample data...once again, this code creates an error when data rows are greater than 14:

Nokia P/N      Description      Models      Tessco      U4      U1      PrcSrc      Category      SrvcLvL      Region      SpclHndlng      CaseMultiples      MOQ      InitBuyQty      RptDte
'4355709      PW AMP PF08125B-04 GSM900/1800/1900      '3100,6100      1.32      1.98      1.99      Matcoma      Spare part      3      ALL      NULL      0                                                                                                                                                                                                                                                                    0                                                                                                                                                                                                                                                                    0      2007-04-16 00:00:00.000
'5409251      SM BATTERY CONN 3POLE SPR      'N73      0.16      0.24      0.24      Matcoma      Spare Part      2      ALL      NULL      0                                                                                                                                                                                                                                                                    0                                                                                                                                                                                                                                                                    0      2007-04-16 00:00:00.000
'0269290      SLIDE ASSEMBLY SILVER 025135 P2912      '5300      2.78      4.17      4.20      Matcoma      Spare Part      1      ALL      NULL      0                                                                                                                                                                                                                                                                    0                                                                                                                                                                                                                                                                    0      2007-04-16 00:00:00.000
'9799738      KEYMAT ASSY LATIN VODAFONE P2906      '2610      1.21      1.82      1.83      Matcoma      Spare Part      1      NAM      NULL      0                                                                                                                                                                                                                                                                    0                                                                                                                                                                                                                                                                    0      2007-04-16 00:00:00.000
'0251927      A-COVER ASSY BLACK PRINTED AT&T P2906      '2610      1.14      1.71      1.72      Matcoma      Spare Part      1      NAM      NULL      0                                                                                                                                                                                                                                                                    0                                                                                                                                                                                                                                                                    0      2007-04-16 00:00:00.000
0
malc77Author Commented:
Expert,

Thanks for your time and efforts...I have decided to use SSRS to deliver my reporting needs....
0
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.