Search code examples
mysqlvb.netword-automation

How to export data into a word document, not the SQL Query? VB.NET


I have been having a difficult time trying to figure this out. I wrote a SQL query to select certain data that has a relationship to a particular institution. Now the SQL query works perfectly fine as I tested it in MySQL Workbench, however, when I try to export that data from VB.NET onto a word document, it literally prints out the SQL.

Below is my code:

    Dim sqlAdapter As New MySqlDataAdapter
    Dim sqlCommand As New MySqlCommand
    Dim sqlTable As New DataTable

    Dim sqlFundText As String = "select mutual_Fund_name, concat(contact_first_name,' ',contact_last_name) from mutual_fund mf, contact c, mutual_fund_has_contact mfhc, institution i, institution_has_mutual_Fund ihmf where mf.mutual_fund_id = mfhc.mutual_fund_id and c.contact_id = mfhc.contact_id and ihmf.mutual_fund_id = mf.mutual_fund_id and i.institution_id = ihmf.institution_id and i.institution_name ='" & InstitutionNameTextBox.Text & "' order by mutual_fund_name;"

    With sqlCommand
        .CommandText = sqlFundText
        .Connection = sConnection
    End With

    With sqlAdapter
        .SelectCommand = sqlCommand
        .Fill(sqlTable)
    End With

    oPara9 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range)
    With oPara9
        .Range.Font.Bold = False
        .Range.Text = sqlFundText
        .Range.Font.Size = 10
        .Format.SpaceAfter = 5
        .Range.InsertParagraphAfter()
    End With

And the result is:

enter image description here

As you can see it prints out the SQL statement.

I know it has to do with the

.Range.Text = sqlFundText

I just do not know how to fix it. Can anyone direct me the right way in fixing this?


Solution

  • The data from your query is in sqlTable. You'll need to extract the data from the data table and add that to your document instead of sqlFundText.

    After your With sqlAdapter ... End With block you'll need to do something like:

    Dim fundName as String
    Dim contactName as String
    For Each row in sqlTable.Rows
        fundName = row[0].ToString()
        contactName = row[1].ToString()
        ' Do something to put fundName and contactName into the document
    Next