Hi All,I am exporting data from SQL to Excel files.My main objective is to - Using column names from SQL table as column headers
- Remove existing data from the old excel file
- Expanding the column width so that all the data is visible when the file is opened. The reason why this is important is because the same excel file is used in a MS Word document as a linked object and if the columns are not wide enough in excel then data stays hidden in the Word file thus not coming out in print outs
I have managed to do above two tasks from the list using the following code: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 recordsetdeclare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)select @columns=coalesce(@columns+',','')+column_name+' as '+column_name from information_schema.columnswhere table_name=@table_nameselect @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')--Create a dummy file to have actual dataselect @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'--Generate column names in the passed EXCEL fileset @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''exec(@sql)--Generate data in the dummy fileset @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''exec(@sql)--Copy dummy file to passed EXCEL fileset @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''exec(@sql)--Delete dummy file set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''exec(@sql)
Reference: [url]http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926&whichpage=1[/url]Can anyone suggest me any more options I can use with BCP command or anything else to achieve the last step?Thanks