Beyondrelational

Wednesday, June 9, 2010

How to import/export data to Excel?

Execute the following script to export table data into an Excel worksheet and import the data back into a table:
use AdventureWorks

-- export
-- the target empty worksheet should exist with header line only

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=F:\data\test\NameAddress.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
select FirstName,
LastName,
EmailAddress,
Phone
from Person.Contact
go

-- import
select * into tempdb.dbo.NameAddress
from OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=F:\data\test\NameAddress.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
go

use tempdb
select * from dbo.NameAddress
go

No comments:

Post a Comment