Solved

Export to Excel Stored Procedure Fails

Posted on 2007-03-29
10
971 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
  • 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
 

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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Nowadays, some of developer are too much worried about data. Who is using data, who is updating it etc. etc. Because, data is more costlier in term of money and information. So security of data is focusing concern in days. Lets' understand the Au…
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.
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…
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

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

11 Experts available now in Live!

Get 1:1 Help Now