Solved

Export to Excel Stored Procedure Fails

Posted on 2007-03-29
10
1,021 Views
Last Modified: 2008-01-09
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
0
Comment
Question by:malc77
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
10 Comments
 
LVL 50

Expert Comment

by:Lowfatspread
ID: 18819138
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
 

Author Comment

by:malc77
ID: 18819206
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
 
LVL 50

Expert Comment

by:Lowfatspread
ID: 18819465
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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 

Author Comment

by:malc77
ID: 18819679
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
 
LVL 50

Accepted Solution

by:
Lowfatspread earned 500 total points
ID: 18819718
sorry
exec DisplayOAErrorInfo @range,@hr
0
 

Author Comment

by:malc77
ID: 18819801
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
 
LVL 50

Expert Comment

by:Lowfatspread
ID: 18821756
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
 

Author Comment

by:malc77
ID: 18823760
Checking......
0
 

Author Comment

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

Author Comment

by:malc77
ID: 18934310
Expert,

Thanks for your time and efforts...I have decided to use SSRS to deliver my reporting needs....
0

Featured Post

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
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…
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

734 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