Visual Basic .NET Forums  
Click here to advertise with us

Go Back   Visual Basic .NET Forums > Database > Database General Discussion

Database General Discussion General discussion on database related topics

VB.NET Forums Newsletter Signup:
Email address:


Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 02-08-2010, 9:46 AM
VB.NET Forum Newbie
.NET Framework: .NET 2.0
 
Join Date: Feb 2010
Age: 27
Posts: 1
Reputation: 0
GrahamK is on a distinguished programming path ahead
Default Exporting SQL Query Results out to Excel

Dear All,

I wonder if you can help me please? I am taking an old VBA/VB6 project and converting it into VB.NET. But I have a couple of problems and can't see how to fix them!

The whole code for the module is below:

Code:
Public Class frmReportBusUnit

    Private Sub frmReportBusUnit_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        On Error GoTo Errhand
        'TODO: This line of code loads data into the 'ServerInfoDataSet.tblBusUnit' table. You can move, or remove it, as needed.
        Me.TblBusUnitTableAdapter.Fill(Me.ServerInfoDataSet.tblBusUnit)
Errhand:
        If Err.Number = 0 Or Err.Number = 20 Then
            Resume Next
        Else
            MsgBox(Err.Number & " " & Err.Description)
            Exit Sub
        End If
    End Sub

    Private Sub cmdReport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReport.Click
        On Error GoTo Errhand

        Dim strsql As String
        Dim cn As New SqlConnection
        Dim cmd As SqlCommand
        Dim strconnect As String
        Dim fldCount As Integer
        Dim recCount As Long
        Dim recArray As Object

        Dim iCol As Integer
        Dim iRow As Integer
        Dim xlApp As Object
        Dim xlWb As Object
        Dim xlWs As Object
        Dim intselected As Integer

        intselected = ComboBox1.SelectedValue

        strconnect = "Data Source=VTG002971;Initial Catalog=ServerInfo;Integrated Security=SSPI;"
        strsql = "SELECT tblCIDetails.DeviceID, tblCIDetails.Asset_Number, tblDevTypes.DevTypeDesc, tblCIStatus.CI_Status, tblBusUnit.BusUnit, tblEstablishment.EstablishmentName, tblBuilding.BuildingName, tblOfficeNames.OfficeName, tblDomain.DomainDesc " & _
        "FROM tblCIStatus RIGHT JOIN (tblBusUnit RIGHT JOIN (((tblDevTypes RIGHT JOIN (tblOfficeNames RIGHT JOIN (tblCIDetails LEFT JOIN tblBuilding ON tblCIDetails.Building = tblBuilding.BuildingID) ON tblOfficeNames.OfficeID = tblCIDetails.Office) ON tblDevTypes.DevTypeID = tblCIDetails.Device_Type) LEFT JOIN tblDomain ON tblCIDetails.Domain = tblDomain.DomID) LEFT JOIN tblEstablishment " & _
        "ON tblCIDetails.Establishment = tblEstablishment.EstablishmentID) ON tblBusUnit.BUID = tblCIDetails.Business_Unit) ON tblCIStatus.Status_ID = tblCIDetails.Device_Status " & _
        "Where tblCIDetails.Business_Unit = " & intselected & ";"

        cn = New SqlConnection(strconnect)
        cmd = New SqlCommand(strsql)

        cmd.Connection = cn
        cmd.Connection.Open()

        Dim myData As SqlDataReader = cmd.ExecuteReader()

        xlApp = CreateObject("Excel.Application")
        xlWb = xlApp.Workbooks.Add
        xlWs = xlWb.Worksheets("Sheet1")

        xlApp.Visible = True
        xlApp.UserControl = True

        ' Copy field names to the first row of the worksheet
        fldCount = myData.FieldCount
        For iCol = 1 To fldCount
            xlWs.Cells(1, iCol).Value = myData.GetName(iCol - 1)
        Next

        ' Check version of Excel
        If Val(Mid(xlApp.Version, 1, InStr(1, xlApp.Version, ".") - 1)) > 8 Then
            'EXCEL 2000,2002,2003, or 2007: Use CopyFromRecordset

            ' Copy the recordset to the worksheet, starting in cell A2
            xlWs.Cells(2, 1).CopyFromRecordset(myData)
            'Note: CopyFromRecordset will fail if the recordset
            'contains an OLE object field or array data such
            'as hierarchical recordsets

        Else
            'EXCEL 97 or earlier: Use GetRows then copy array to Excel

            ' Copy recordset to an array
            recArray = myData.GetRows
            'Note: GetRows returns a 0-based array where the first
            'dimension contains fields and the second dimension
            'contains records. We will transpose this array so that
            'the first dimension contains records, allowing the
            'data to appears properly when copied to Excel

            ' Determine number of records

            recCount = UBound(recArray, 2) + 1 '+ 1 since 0-based array


            ' Check the array for contents that are not valid when
            ' copying the array to an Excel worksheet
            For iCol = 0 To fldCount - 1
                For iRow = 0 To recCount - 1
                    'Take care of Date fields
                    If IsDate(recArray(iCol, iRow)) Then
                        recArray(iCol, iRow) = Format(recArray(iCol, iRow))
                        ' Take care of OLE object fields or array fields
                    ElseIf IsArray(recArray(iCol, iRow)) Then
                        recArray(iCol, iRow) = "Array Field"
                    End If
                Next iRow 'next record
            Next iCol 'next field

            ' Transpose and Copy the array to the worksheet,
            ' starting in cell A2
            xlWs.Cells(2, 1).Resize(recCount, fldCount).Value = _
            TransposeDim(recArray)
                    End If

        ' Auto-fit the column widths and row heights
        xlApp.Selection.CurrentRegion.Columns.AutoFit()
        xlApp.Selection.CurrentRegion.Rows.AutoFit()

        ' Close ADO objects
        'rst.Close()
        'cnt.Close()
        'rst = Nothing
        'cnt = Nothing

        ' Release Excel references
        xlWs = Nothing
        xlWb = Nothing

        xlApp = Nothing


        cn.Close()
        myData.Close()

        myData = Nothing
        cn = Nothing


Errhand:
        If Err.Number = 0 Or Err.Number = 20 Then
            Resume Next
        Else
            MsgBox(Err.Number & " " & Err.Description)
            Exit Sub
        End If
    End Sub
I have a couple of errors - the first is that on the line "recArray = myData.GetRows"

I get the error : "Error 1 'GetRows' is not a member of 'System.Data.SqlClient.SqlDataReader'."

I would appreciate any help that can be offered!

Many THanks
Graham
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 02-09-2010, 5:21 AM
cjard's Avatar
VB.NET Forum All-Mighty
.NET Framework: .NET 2.0 (VS 2005)
 
Join Date: Apr 2006
Age: 65
Posts: 6,442
Reputation: 807
cjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond repute
Default

Dump most of that code. Transport the sql query into a tableadapter in a dataset or at the very least, into a dataadapter (read the PQ link in my signature too). Use the attached project and either convert the code from C# or reference the included DLL in your project (or if you have full studio just add it as a project to your solution, if you have vb express, you can use c# express to compile a new DLL if you think it wiser/trust aspects) to add the ability for your datatables to write xml files that will load straight into Excel. You have to recompile the DLL to alter the formatting defaults (settings are compiled into DLLs)

Then make a new datatable from the ExcelableData project and fill it with data using the adapter described above. Write it to Excel XML and you can open the file for the user to see or just leave it for later
__________________
DW1 DW2 DW3 DW4 DNU PQ
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 02-09-2010, 5:22 AM
cjard's Avatar
VB.NET Forum All-Mighty
.NET Framework: .NET 2.0 (VS 2005)
 
Join Date: Apr 2006
Age: 65
Posts: 6,442
Reputation: 807
cjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond reputecjard has a reputation beyond repute
Default

Here's the attachment
Attached Files
File Type: zip ExcelableData.zip (16.6 KB, 0 views)
__________________
DW1 DW2 DW3 DW4 DNU PQ
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On





All times are GMT -4. The time now is 7:33 AM.

Powered by vBulletin® Version 3.8.5
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.2


For advertising opportunities click here.