Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am using the following code to write values to a datatable and then export it to Excel.

What I am trying to achieve now is to modify the code so that a separate Excel file is saved for each unique customer ([Customer Lookup])

Here is my export code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    'Initialize the objects before use
    Dim dataAdapter As New SqlClient.SqlDataAdapter()
    Dim dataSet As New DataSet
    Dim command As New SqlClient.SqlCommand
    Dim datatableMain As New System.Data.DataTable()
    Dim connection As New SqlClient.SqlConnection

    'Assign your connection string to connection object
    connection.ConnectionString = "server=inlt01\SQLEXPRESS; database=DaisyBilling; integrated security=yes"
    command.Connection = connection
    command.CommandType = CommandType.Text
    'You can use any command select
    command.CommandText = "SELECT [CustomerCLI], [Customer Lookup],ROUND (SUM ([SalesPrice]),2) as [Sum of Buy Price],ROUND (SUM ([Sell Price]),2) as [Sum of Sell Price],[Tariff Lookup] FROM [DaisyBilling].[dbo].[" + DaisyBillingForm.TextBox1.Text + "] GROUP BY [CustomerCLI], [Customer Lookup],[Tariff Lookup] Order by [Customer Lookup]"
    dataAdapter.SelectCommand = command

    Dim f As FolderBrowserDialog = New FolderBrowserDialog
    Try
        If f.ShowDialog() = DialogResult.OK Then
            'This section help you if your language is not English.
            System.Threading.Thread.CurrentThread.CurrentCulture = _
            System.Globalization.CultureInfo.CreateSpecificCulture("en-US")
            Dim oExcel As Excel.Application
            Dim oBook As Excel.Workbook
            Dim oSheet As Excel.Worksheet
            oExcel = CreateObject("Excel.Application")
            oBook = oExcel.Workbooks.Add(Type.Missing)
            oSheet = oBook.Worksheets(1)

            Dim dc As System.Data.DataColumn
            Dim dr As System.Data.DataRow
            Dim colIndex As Integer = 0
            Dim rowIndex As Integer = 0

            'Fill data to datatable
            connection.Open()
            dataAdapter.Fill(datatableMain)
            connection.Close()

            'Export the Columns to excel file
            For Each dc In datatableMain.Columns
                colIndex = colIndex + 1
                oSheet.Cells(1, colIndex) = dc.ColumnName
            Next

            'Export the rows to excel file
            For Each dr In datatableMain.Rows
                rowIndex = rowIndex + 1
                colIndex = 0
                For Each dc In datatableMain.Columns
                    colIndex = colIndex + 1
                    oSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName).ToString()

                Next
            Next

            'Set final path

            Dim fileName As String = "\" + DaisyBillingForm.TextBox1.Text + "_" + DateTime.Now.ToString("ddMMyyyy") & "_" & DateTime.Now.ToString("HHmmss") + ".xls"
            Dim finalPath = f.SelectedPath + fileName
            'TextBox1.Text = finalPath
            oSheet.Columns.AutoFit()

            'Save file in final path
            oBook.SaveAs(finalPath, XlFileFormat.xlWorkbookNormal, Type.Missing, _
            Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, _
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)

            'Release the objects
            ReleaseObject(oSheet)
            oBook.Close(False, Type.Missing, Type.Missing)
            ReleaseObject(oBook)
            oExcel.Quit()
            ReleaseObject(oExcel)
            'Some time Office application does not quit after automation: 
            'so i am calling GC.Collect method.
            GC.Collect()

            MessageBox.Show("Export done successfully!")

        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK)
    End Try
End Sub

How can I create a loop and run this code per unique customer and save a separate file for each?

I am relatively new to VB, any help greatly appreciated.

Thanks,

share|improve this question
    
Write a query to fill a dataset with every customer you have. Than add a loop For Each Customer in Customers at the beginning of the button click event. –  Hoh Aug 23 at 18:47
    
Will that work if the customer list is dynamic? –  user3580480 Aug 23 at 18:51
    
Well if you don't have a lot of customers, you can always clear dataset and fill it again (in button click event). –  Hoh Aug 23 at 18:51
    
Ok, I am relatively new to vb.net, so if you could provide a code example that would be great. Thanks –  user3580480 Aug 23 at 19:08
    
THIS is actually a great way to learn about FOR EACH loop, and will be very useful for you to solve your problem. –  Hoh Aug 23 at 19:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.