In the post Import/Export to Excel, I showed how to export data to EXCEL
The problem that most users find it is it wont include column names in the file and file should exists already with headings
This procedure would solve that problem
create procedure proc_generate_excel_with_columns
(
@db_name varchar(100),
@table_name varchar(100),
@file_name varchar(100)
)
as
--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100) select@columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')
--Create a dummy file to have actual data
--Generate column names in the passed EXCEL file
exec(@sql)
--Generate data in the dummy file
exec(@sql)
--Copy dummy file to passed EXCEL file
exec(@sql)
--Delete dummy file
exec(@sql)
After creating the procedure, execute it by supplying database name, table name and file path
EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'
For more informations and to know how to solve the errors, refer this thread Export to Excel
Source Click Here.


Post a Comment