Click here to Skip to main content
Click here to Skip to main content

Dynamically Generating Html/Excel/Word Document Files with SQL Server data using SSIS 2005

By , 11 Jan 2012
 

Introduction

This article is intended primarily for intermediate to advanced SSIS (SQL Server Integration Services) users who are familiar with SQL Server Business Intelligence. Basic understanding of script task, Execute Sql Task, parameters and variables are required, as it is not exactly a tutorial, but a description of the implementation of exporting the database table objects to HTML/Excel/Word documents using SSIS. This package will help to migrate data in a well formatted HTML files in simple and efficient way. The Goal of this article is to help the users by providing the concept to create either HTML/Excel/Word document files with all the data from the SQL Sever database tables with a better presentation and good look and feel without the need of any templates, DLL's and much of programming.

This package is basically to demonstrate a method of data migration to export SQL Server tables to well formatted static HTML pages. Here is the simple DTSX package which creates either an HTML/Excel file on the fly based on the variable value settings. The package is developed using Visual Studio 2005.

Below is the demonstration of the steps to achieve this.

The dtsx package should look like the above Image.

Background

The above package uses the SP_MAKEWEBTASK SQL Server Object for creating the Html files. This SQL Server object does all the HTML presentation & formatting including table name as heading.

For more information on the SP_MAKEWEBTASK functionality and its options refer online documentation at the following link http://msdn.microsoft.com/en-us/library/aa238843(v=sql.80).aspx

Using the code

The ServerOption should be turned on, these 'DATA ACCESS' and 'Web Assistant Procedures' options needed to be reconfigured on the SQL Server before running the package. The package will fail without these Options. And importantly the database login should have admin privileges to execute the package tasks successfully. These options are currently set in the following task.

[Get List of Tables to Process] Execute SQL Task: The query is to retrieve all the table names. (Customize this query as per your requirement.)

/********************************************************************** 
 CREATED BY      : VENKAT CHAITANYA KANUMUKULA 
 CREATED ON      : This is created and tested in SQL SERVER 2000 and SQL SERVER 2005.
 PURPOSE      : This Object is get the List of Tables from the Database.
 COMMENTS     : So that it can be used for creating objects in xls file via SSIS.
                Tested on SQL Server 8.00.194 - RTM (Desktop Engine) ,SQL Server 9.00.4035.00 - SP3 (Developer Edition)
 SSIS TASK    : [Get List of Tables to Process] SSIS Execute SQL Task   
 **********************************************************************/

DECLARE @Server varchar(50) 
SET @Server = @@SERVERNAME 
-- This ServerOption Should be Turned on the Server. Not required every time.
EXEC sp_serveroption  @Server,'DATA ACCESS','TRUE'

SELECT [TableName] = so.name 
                FROM sysobjects so, sysindexes si 
                WHERE so.xtype = 'U' AND si.id = OBJECT_ID(so.name)
/*Uncomment the following line if you are using Excel 2003.*/
                --AND si.rows < 65335 
/*Uncomment the following code if you want to avoid the table names where you dont have data in it.*/
                --AND si.rows > 0
                GROUP BY so.name 
                ORDER BY 1 DESC 

-- Comment this later after executing. This is not required every time.
EXEC sp_configure 'Web Assistant Procedures', 1;
RECONFIGURE;  

Change the Variable DestFileType value either HTM , HTML or XLS , XLSX or Doc , Docx as shown in the below image.Change the database connection to SQL Server 2000/2005 and point to the database which you want to export. Change the Variable DestExcelFilePath Value from 'C:\SSIS' for creating a file at the desired location. Package should work properly if all the Table names and Column names are followed as per the microsoft naming standards.

SSIS_Html1.jpg

[Insert Script Generation] ScriptTask: This script task code in VB.NET is to build a query using the SQL Server SP_MAKEWEBTASK function which finally creates the files in the destination folder with the name either (TableName.Html/TableName.xls/TableName.doc or etc) based on the DestFileType variable value is set to.

Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime

Public Class ScriptMain

    Public Sub Main()
        ' CREATED BY      : VENKAT CHAITANYA KANUMUKULA 
        ' 
        '
        Dim excelFilePath As String = CStr(Dts.Variables("User::DestExcelFilePath").Value) 
               '+ CStr(Dts.Variables("DestExcelFileName").Value)
        Dim TableName, ExcelTable, FileType As String
        TableName = CStr(Dts.Variables("User::ExcelTable").Value)

        FileType = CStr(Dts.Variables("User::DestFileType").Value)

        If TableName.Length > 30 Then
            ExcelTable = Strings.Left(TableName, 31)
            'Excel sheet Name can only be 30 characters length.
        Else
            ExcelTable = TableName
        End If

        ' The sp_serveroption has to be set to TRUE on the Server for running SP_MAKEWEBTASK.
        ' To avoid runtime errors in column names replace '*' with column names in brackets[].

        Dim strCn As String = "EXEC  sp_makewebtask  " & _
        "@outputfile = '" + excelFilePath + ExcelTable + "." + FileType + "', " & _
        "@query = 'SELECT * FROM dbo.[" + TableName + "]', " & _
        "@colheaders =1,@FixedFont=0,@lastupdated=0," & _
        "@resultstitle= '" + TableName + " Table '"

        Dts.Variables("User::InsertScripter").Value = strCn
        Dts.TaskResult = Dts.Results.Success
    End Sub

End Class

Conclusion

The above mentioned demonstration of steps determine that multiple HTML/XLS/Word document files along with data migration from SQL Server can be dynamically created using SSIS 2005. Its not a good Idea to export a huge database with the above package where it might end up using the system memory and other resources.

SSIS_Html2.jpg

Hence it can be concluded that exporting the database table objects to a HTML/Excel/Word document files is achieved through easy steps in SSIS with a minimum programming.

If the DestFileType variable value is set to XLS or XLSX. It should look like the below image.

SSIS_Html3.jpg

Note: When the Variable DestFileType value is set to XLS or XLSX the following script task will create the excel file but with html body inside it.

If the DestFileType variable value is set to HTM or HTML. It should look like the below image.

SSIS_Html4.jpg

If the DestFileType variable value is set to DOC or DOCX. It should look like the below image.

SSIS_Html5.jpg

Note: When the Variable DestFileType value is set to DOC or DOCX the following package will create the Word document file but with html body inside it.

The file extensions are not limited to above mentioned. If you are using Open office there are various other extension available.

The above images are provided as a sample just to show how the formatting and presentation of output files look like after exporting the tables to HTML ,Excel and Word document files.

Hope this article will serve the purpose. Any suggestions or corrections are most welcome.

Points of Interest

Reverse Engineering, Up-gradations, Conversions, Integrations and Data migration.

References

http://msdn.microsoft.com/en-us/library/aa238843(v=sql.80).aspx

History

9 Th Jan 2012

4 Th Jan 2012

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Venkat Chaitanya Kanumukula
Software Developer (Senior)
India India
Member
He is a lead software developer, and has been in the industry since Oct 1997. Currently working on Dealership Management System using Microsoft Dynamics AX 2012( Inc - Visual Studio 2010, SharePoint 2010, SQL Server 2008, MS Windows Server 2008 and etc).

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionIf the database and application are on two different serversmemberaneesh_kamble13 May '13 - 20:25 
Hi Venkat,
Very nice article. Thanks.
But, If I want to store the generateed html file in my application server, how can i do it?
 
Lets say, the database and the application are on two different server.
So, If I want to store the html file created by SSIS on my application server, how can i do it.
 
For this, I think I will have to introduce a extra overhead service for copying the Html file in application server.
 
Help needed..
 
Thanks
GeneralMy vote of 5membermanoj kumar choubey1 Apr '12 - 22:14 
Nice
Question.NET waymemberJamesHoward97210 Jan '12 - 22:05 
To me, report generation was always application task and not database task.
 
With this Excel C# / VB.NET library, I can easily export entire DataSet to Excel like this:
var ef = new ExcelFile();
 
foreach (DataTable dataTable in dataSet.Tables)
    ef.Worksheets.Add(dataTable.TableName).InsertDataTable(dataTable, 0, 0, true);
 
ef.SaveXls(dataSet.DataSetName + ".xls");

AnswerRe: .NET way [modified]memberVenkat Chaitanya Kanumukula11 Jan '12 - 4:34 
There are lots of validations along with data migration and report generation occur with SSIS. your code does not help SSIS users. That's where these tasks mentioned in the article come in handy.

-- modified 11 Jan '12 - 15:41.
QuestionCould not find stored procedure 'sp_makewebtask'memberSukh Veer Singh10 Jan '12 - 19:18 
when i execute this sp in SQl Server 2008 it give me error "Could not find stored procedure 'sp_makewebtask'".Can u tell if I Could not find stored procedure 'sp_makewebtask' then how to create stored procedure 'sp_makewebtask' in sql server 2008
AnswerRe: Could not find stored procedure 'sp_makewebtask' [modified]memberVenkat Chaitanya Kanumukula11 Jan '12 - 4:59 
This feature is deprecated in 2008 by microsoft. Cannot use that with Database 2008 anymore.
Try this package instead   http://www.codeproject.com/KB/database/Dynamic_Excel.aspx to export to excel.
 
There are few links where others have created using T-SQL. but I wouldn't suggest since they were not been tested on 2008. Cheers! Smile | :)

-- modified 11 Jan '12 - 15:54.
GeneralMy vote of 3memberKacha Jatin10 Jan '12 - 18:03 
good article
QuestionIn Christmas comes, in order to thank everyone, characteristic, novel style, varieties, low price and good quality, and the low sale price. Thank everyone ====( http://www.fullmalls.com )===== ====( http://www.fullmalls.com )===== $33 True Religgroupsghjyuk7 Jan '12 - 1:12 
In Christmas comes, in order to thank everyone, characteristic, novel style, varieties, low price and good quality, and the low sale price. Thank everyone
 

====( http://www.fullmalls.com )=====
 
====( http://www.fullmalls.com )=====
 

$33 True Religion jeans, Ed Hardy jeans,LV,Coogi jeans,Affliction jeans
 
$30 Air Jordan shoes,Shox shoes,Gucci,LV shoes
 
50%Discount winter fashion :Sandle,t-shirt,caps,jerseys,handbag and brand watches!!!
 
$15 Ed Hardy ,LV ,Gucci Bikini
 
$15 Polo, Ed Hardy, Gucci, LV, Lacoste T-shirts
 
$25 Coach,Gucci,LV,Prada,Juicy,Chanel handbag,
 
$10 Gucci,Ed Hardy sunglasses
 
$9 New Era caps.
 
give you the unexpected harvest
 
====( http://www.fullmalls.com )=====
 
====( http://www.fullmalls.com )=====
 
====( http://www.fullmalls.com )=====
 
====( http://www.fullmalls.com )=====
 
====( http://www.fullmalls.com )=====
 
====( http://www.fullmalls.com )=====

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 11 Jan 2012
Article Copyright 2012 by Venkat Chaitanya Kanumukula
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid