Results 1 to 1 of 1

Thread: Export Data from SQL Database into Excel Spreadsheet

Threaded View

  1. #1

    Thread Starter
    Lively Member
    Join Date
    May 2004
    Posts
    104

    Export Data from SQL Database into Excel Spreadsheet

    I just want to say thanks to all of you guys out there. All of you guys have assisted me at one time or another especially doing searches. The only way I know how to give back is to post some code.

    This code basically builds an sql query from some controls, and then pulls the data from a sql database and transports it to excel. If you have any questions feel free to post.

    Begin the SELECT statement

    VB Code:
    1. Public Function Begin_Query()
    2.         Dim selectWhat As String
    3.         Dim i As Integer
    4.         Dim k As Integer
    5.         Dim maxValue As Integer
    6.         maxValue = chkFields.Items.Count - 1
    7.         Dim indexvalue(maxValue) As String
    8.         Dim counter As Integer
    9.         For i = 0 To maxValue
    10.             If chkFields.Items(i).Selected Then
    11.                 counter = counter + 1
    12.                 indexvalue(counter - 1) = chkFields.Items(i).Value
    13.             End If
    14.         Next
    15.         For k = 0 To counter - 1
    16.             If k = counter - 1 Then
    17.                 selectWhat = selectWhat & indexvalue(k)
    18.             Else
    19.                 selectWhat = selectWhat & indexvalue(k) & ", "
    20.             End If
    21.         Next
    22.         Return selectWhat
    23.     End Function

    Now the conditions associated with the query

    VB Code:
    1. Public Function Conditional_Query()
    2.         Dim conditions As String
    3.         Dim fieldname As String
    4.         Dim conditiontype As String
    5.         Dim expression As String
    6.         fieldname = cmbFields.SelectedItem.Value
    7.         conditiontype = cmbCondition.SelectedItem.Value
    8.         expression = txtCondition.Text
    9.         If fieldname = "NONE" Or conditiontype = "NONE" Then
    10.             Return conditions
    11.         ElseIf conditiontype = "LIKE" Then
    12.             conditions = "WHERE (" & fieldname & " " & conditiontype & " '%" & txtCondition.Text & "%')"
    13.         Else
    14.             conditions = "WHERE (" & fieldname & " " & conditiontype & " '" & txtCondition.Text & "')"
    15.         End If
    16.         Return conditions
    17.  
    18.     End Function

    Now end the query

    VB Code:
    1. Public Function Orderby_Query()
    2.         Dim sorting As String
    3.         Dim sortby As String
    4.         sortby = cmbSort.SelectedItem.Value
    5.         If sortby = "NONE" Then
    6.  
    7.         Else
    8.             sorting = " ORDER BY " & sortby & ""
    9.         End If
    10.         Return sorting
    11.     End Function

    Now the export function.. Note: I did do a search on Excel and found the way to pull the stuff out so I dont get credit for that part of the code. I cannot remember who posted it but they did an excellent job.

    VB Code:
    1. Public Function Export_Excel(ByVal Query As String)
    2.  
    3.         Dim sqlconn As SqlConnection = New SqlConnection
    4.         Dim strConn As String
    5.         strConn = "Server=SERVERNAME;Database=dbname;User ID=USER;Password=PASSWORD"
    6.         sqlconn.ConnectionString = strConn
    7.         sqlconn.Open()
    8.         'File control.  Have to delete the file if it already exists otherwise create it.  Its easier just to delete the file rather than check to see if its already there.
    9.         Dim dir As Directory
    10.         Dim dirfile As File
    11.         Dim pathname As String
    12.         Dim title As String
    13.         If txtFilename.Text = "" Then
    14.             title = "cl"
    15.         Else
    16.             title = txtFilename.Text
    17.         End If
    18.         pathname = "C:\Inetpub\wwwroot\Workorders\" & title & ".xls"
    19.         Dim filepath As String
    20.         Dim i As Integer
    21.         filepath = Server.MapPath(Request.ApplicationPath) & "\" & title & ".xls"
    22.         dirfile.Delete(pathname)
    23.         'Bind the dataset to the results returned from the DataAdapter.
    24.         Dim sAdapter As New SqlDataAdapter(Query, sqlconn)
    25.         Dim ds As New DataSet
    26.         sAdapter.Fill(ds, "cl")
    27.  
    28.         'Start the Excel Sheet Declarations and initiate the spreadsheet
    29.         Dim xl As Excel.Application
    30.         Dim oBook As Excel.Workbook
    31.         Dim oSheet As Excel.Worksheet
    32.         xl = CreateObject("Excel.Application")
    33.         oBook = xl.Workbooks.Add
    34.         oBook.Worksheets.Add()
    35.         oSheet = CType(oBook.Worksheets(1), Excel.Worksheet)
    36.         oSheet.Name = title
    37.         oSheet.Range("A:Z").ColumnWidth = 30
    38.         xl.Visible = True
    39.  
    40.         'Start filling in data from database.  Cannot take credit for this part.
    41.         Dim iColumn, iRow As Integer
    42.         Dim iColumnMax, iRowMax As Integer
    43.         iRowMax = ds.Tables(0).Rows.Count - 1
    44.         iColumnMax = ds.Tables(0).Columns.Count - 1
    45.         For iRow = 0 To iRowMax
    46.             For iColumn = 0 To iColumnMax
    47.                 oSheet.Cells(iRow + 3, iColumn + 1) = ds.Tables(0).Rows(iRow).Item(iColumn)
    48.             Next
    49.         Next
    50. 'Thank you vbforums for that little bit of code.
    51.         'Start looping through the items that are selected.  If they are selected add them to a different array with a different index.
    52.         Dim maxValue As Integer
    53.  
    54.         maxValue = chkFields.Items.Count - 1
    55.         Dim counters As Integer
    56.         Dim itemtext(maxValue) As String
    57.         Dim itemvalue(maxValue) As String
    58.         For i = 0 To maxValue
    59.             If chkFields.Items(i).Selected Then
    60.                 counters = counters + 1
    61.                 itemtext(counters - 1) = chkFields.Items(i).Text
    62.                 itemvalue(counters - 1) = chkFields.Items(i).Value
    63.             End If
    64.         Next
    65.  
    66.  
    67.         'Customize the spreadsheet's cells
    68.         Dim counter As Integer
    69.         For counter = 0 To iColumnMax
    70.             oSheet.Cells(2, counter + 1).Font.Bold = True
    71.             oSheet.Cells(2, counter + 1).Font.Size = 14
    72.             oSheet.Cells(2, counter + 1).Interior.Color = &H808080
    73.             oSheet.Cells(2, counter + 1).Value = itemtext(counter)
    74.         Next
    75.  
    76.         oSheet.Cells(1, 3).Value = title
    77.  
    78.         oSheet.Cells(1, 3).Font.Bold = True
    79.         oSheet.Cells(1, 3).Font.Italic = True
    80.         oSheet.Cells(1, 3).Font.Size = 14
    81.         oSheet.Cells(1, 3).Interior.Color = &H808080
    82.         oSheet.Cells(1, 1).Interior.Color = &H808080
    83.         oSheet.Cells(1, 2).Interior.Color = &H808080
    84.         oSheet.Columns.AutoFit()
    85.         oSheet.Activate()
    86.  
    87.  
    88.  
    89.         'Save and display the object
    90.         oSheet.SaveAs(filepath)
    91.         Send_Mail(Query, title)
    92.         xl.DisplayAlerts = True
    93.        
    94.         'Cleanhouse
    95.         xl.Quit()
    96.         ReleaseComObject(oSheet)
    97.         ReleaseComObject(oBook)
    98.         ReleaseComObject(xl)
    99.  
    100.         ds = Nothing
    101.         xl = Nothing
    102.         oBook = Nothing
    103.         oSheet = Nothing
    104.         System.GC.Collect()
    105.  
    106.         Response.Redirect(title & ".xls")
    107.         sqlconn.Close()
    108.  
    109.     End Function
    And the last function here is to send an email based on what you logged in as. This will also send you a hyperlink to the report that was generated.

    VB Code:
    1. Public Function Send_Mail(ByVal Query As String, ByVal title As String)
    2.         Dim eaddress, aaddress As String
    3.  
    4.         eaddress = Session("Usernme")
    5.         Select Case eaddress
    6.             Case "name1"
    7.                 aaddress = "[email protected]"
    8.             Case "name2"
    9.                 aaddress = "[email protected]"
    10.             Case "name3"
    11.                 aaddress = "[email protected]"
    12.             Case Else
    13.                 aaddress = "[email protected]"
    14.         End Select
    15.         Dim dayt, timed As String
    16.         dayt = Now.Date
    17.         timed = Now.TimeOfDay.ToString
    18.         Dim message As String
    19.         Dim email As New MailMessage
    20.         SmtpMail.SmtpServer = "IP OR NAME OF SERVER"
    21.         message = "A new report has been generated with the query being " & Query & ".  The report was ran " & dayt & " at " & timed & ".  You may find this report at the following location http://servername/direcname/" & title & ".xls."
    22.         email.From = "[email protected]"
    23.         email.To = aaddress
    24.         email.Subject = "Report generated from table call log."
    25.         email.Body = message
    26.         SmtpMail.Send(email)
    27.  
    28.     End Function
    NOTE: This code isnt finished by any means. This is a somewhat finished state. I know I need to clean it up a lot but I wanted to post while I was still tingling a little bit. The code has been tested and it works perfect for what my boss needs.
    Last edited by Hack; Dec 8th, 2005 at 11:07 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width