Saturday, December 3, 2011

How to export data from database table to Excel sheet and Datatable

How to export data from database table to Excel sheet and Datatable

‘  Adding NewDataSheet in Run Time
DataTable.AddSheet “MySheet”

‘ ‘  Adding Column name in Run time
DataTable.GetSheet(“MySheet”).AddParameter “bname”,” “
‘ Create DataBase Connection
Set objCon = CreateObject(“ADODB.Connection”)
objCon.Open”Provider=SqlOledb.1;Server=sys;uid=sa;pwd=;database=db1″
‘ (OR)  Open DataBase Connection

objCon.Open”Provider=Microsoft.Jet.Oledb.4.0;Data Source=D:\NewDB.mdb”

‘  Creating Record set for DataSet
Set objRs=CreateObject(“adodb.recordset”)

‘ Opening RecodSet form DataBase( storing the values in recordsetb )
objRs.open”select * from Emp”,objCon

‘ Loop for Getting DataBase Column name
For intCount = 1 to objRs.Fields.Count-1
i = 1

‘ column name in run time data sheet using add parameter method
DataTable.GetSheet(“MySheet”).AddParameter objRs.Fields(intCount).Name,” “
‘ Loop for Checking end of the Recod
While objRs.eof<>true
‘  Seting the current row
DataTable.SetCurrentRow(i)
‘   inc’ents for data table row
i=i+1
‘  Assigning the DataBase Values into DataTable
DataTable.Value(objRs.Fields(intCount).Name,”MySheet”) = objRs.Fields(intCount).Value
‘’ ——->  moving the record  pointed to next record
objRs.MoveNext
Wend
‘  moving the record  pointed to First record
objRs.MoveFirst
Next
‘ Exporting the results in local
DataTable.ExportSheet”D:\HPQTPForum.xls”,3

No comments:

Post a Comment