I modified the HTML generating portion of the code to handle column names with spaces and numbers, and also column values with numeric values that might also have null values. The code also uses varchar(max) instead of varchar(8000). This portion is shown here encapsulated in its own stored proc. It writes the results to a temp table.
CREATE PROC [QueryToHTML](@Query Varchar(MAX))
AS BEGIN
DECLARE @Columns VARCHAR(MAX)
DECLARE @ColHeader VARCHAR(MAX)
DECLARE @SqlCmd VARCHAR(MAX)
DECLARE @HTMLBody VARCHAR(MAX)
-- drop temporary tables used.
IF EXISTS ( SELECT *
FROM tempdb.dbo.sysobjects
WHERE name = '##TEMPhtml1' )
DROP TABLE ##TEMPhtml1
IF EXISTS ( SELECT *
FROM tempdb.dbo.sysobjects
WHERE name = '##TEMPhtml2' )
DROP TABLE ##TEMPhtml2
-- prepare query
SET @SqlCmd = 'select * into ##tempHTML1 from (' + @Query + ') as t1'
EXECUTE (@SqlCmd)
--Prepare columns details
SELECT @columns = COALESCE(@columns + ' + ''</td><td>'' + ' , '')
+ 'RTrim(isnull(convert(varchar(100),' + '[' + CONVERT(VARCHAR(100),column_name) + ']'
+ '),'' ''))'
FROM tempdb.information_schema.columns
WHERE table_name = '##tempHTML1'
--Prepare column Header
SET @colHeader = '<tr bgcolor=#EDFEDF align=Left>'
SELECT @colHeader = @colHeader + '<td><b>' + column_name
+ '</b></td>'
FROM tempdb.information_schema.columns
WHERE table_name = '##tempHTML1'
SET @colHeader = @colHeader + '</tr>'
--prepare final output
SET @SqlCmd = 'Select ''<tr><td>'' + ' + @columns
+ ' + ''</td></tr> '' as Cmd into ##tempHTML2 from ##tempHTML1 '
EXECUTE( @SqlCmd);
--set @finalhtmlout=
SET @HtmlBody = ' <html> <body><style type="text/css" media="all"> '
+ 'table { margin: 2em 2em 2em 3em; border-collapse: collapse; width:75%;} '
+ 'td,th {min-width: 55px; border-width: 1px; border-style: none none solid none; border-color: #DCDCDC; padding: 0.2em 0.2em; font-size: 12;} '
+ '</style> <table> ' + @colHeader
SELECT @HtmlBody = @HtmlBody + Cmd + '</td></tr>'
FROM ##tempHTML2
IF EXISTS ( SELECT *
FROM tempdb.dbo.sysobjects
WHERE name = '##HTMLFinal' )
BEGIN
DROP TABLE ##HTMLFinal
END
SELECT @HtmlBody + ' </table></body></htmL>' AS html
INTO ##HTMLFinal
END