Cari Blog Ini

19 Juni 2012

How To Export Data From SQL To Existing File Excel Using OpenRowSet


1. Sample of data
------------------------------------------------------------------
-----code:start
------------------------------------------------------------------
select * from Cabang
------------------------------------------------------------------
-----code:end
------------------------------------------------------------------

Result Messages:
KdCabang Cabang                        
-------- ------------------------------
005      BSD                          
002      JAYAKARTA                    
003      KEBON JERUK                  
004      KELAPA GADING                
007      SURABAYA                     
006      BANDUNG                      
001      PUSAT                        
008      SEMARANG                     

(8 row(s) affected)



2.
A. Prepare for existing file excel.

Example : in Drive D:\, save the name "Testing.xls"

B. Prepare for name of columns.



3. Run this query
------------------------------------------------------------------
-----code:start
------------------------------------------------------------------
INSERT INTO OPENROWSET
    ('Microsoft.Jet.OLEDB.4.0',
    'Excel 8.0;
    Database=D:\Testing.xls;',
    'SELECT KdCabang, Cabang FROM [Sheet1$]')

    SELECT KdCabang, Cabang FROM Cabang
GO
------------------------------------------------------------------
-----code:end
------------------------------------------------------------------

Result Messages:
(8 row(s) affected)


4. Check file excel "Testing.xls" in Drive D:\


Source:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926