datagridview to excel - progressbar vb.net

时间:2016-02-24 14:16:23

标签: vb.net excel datagridview progress-bar

我有一个按钮,让我将数据网格视图导出到Excel。有时它有超过5000行,所以需要更长的时间。

我尝试添加进度条,但它只是随机的(下面的方式)。 如何以更好的方式实现进度条?我不认为我还需要计时器。

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim exeDir As New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName)
    Dim xlPath = IO.Path.Combine(exeDir.DirectoryName, "template.xlsx")
    Dim xlApp As Excel.Application
    Dim xlWorkBook As Excel.Workbook
    Dim xlWorkSheet As Excel.Worksheet
    'Dim rTargetCell As Excel.Range
    Dim misValue As Object = System.Reflection.Missing.Value
    Dim i As Integer
    Dim j As Integer

'TEST!
For i = 0 To i = ProgressBar1.Maximum
    ProgressBar1.Value = i
    ProgressBar1.Update()
    Timer2.Start()
    System.Threading.Thread.Sleep(25)
    Next
'End Test!

xlApp = New Microsoft.Office.Interop.Excel.Application
    xlWorkBook = xlApp.Workbooks.Open(xlPath)
    xlWorkSheet = xlWorkBook.Worksheets("data")

    For i = 0 To DataGridView2.RowCount - 1
        For j = 0 To DataGridView2.ColumnCount - 1
            For k As Integer = 1 To DataGridView2.Columns.Count

                xlWorkSheet.Cells(i + 1, j + 1) = DataGridView2(j, i).Value
            Next
        Next
    Next
xlWorkSheet.SaveAs("C:\Users\User\Desktop\" & TextBox3.Text & ".xlsx")
    xlWorkBook.Close()
    xlApp.Quit()
    Process.Start("C:\Users\User\Desktop\" & TextBox3.Text & ".xlsx")
    Me.Close()
  End Sub


Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
    ProgressBar1.Increment(1)
    Label3.Text = "(...)"
    If ProgressBar1.Maximum = DataGridView2.Rows.Count Then
    Label3.Text = "Finished"
    End If
    Timer2.Stop()
End Sub

2 个答案:

答案 0 :(得分:0)

您可以尝试以下内容。在开始循环之前,您可以将进度条最大值设置为您拥有的总数或记录。

me.progressbar1.maximum = DataGridView2.RowCount 


For i = 0 To DataGridView2.RowCount - 1
    For j = 0 To DataGridView2.ColumnCount - 1
        For k As Integer = 1 To DataGridView2.Columns.Count
            xlWorkSheet.Cells(i + 1, j + 1) = DataGridView2(j, i).Value
        Next
    Next
Me.ProgressBar1.performstep()  'increment your bar with each record
Next

答案 1 :(得分:0)

假设您的进度条从最小值0到最大值100.您应该将要转储的行除以100。

例如在此行For i = 0 To DataGridView2.RowCount - 1

这一行ProgressBar1.Value = Int(i * (ProgressBar1.Maximum / DataGridView2.RowCount)) 然后根据该行放置此行以确保视图更新,因为您没有在单独的线程上运行进度条更新。My.Application.DoEvents()

所以看起来应该是这样的

For i = 0 To DataGridView2.RowCount - 1

   ProgressBar1.Value = Int(i * (ProgressBar1.Maximum / DataGridView2.RowCount))
    My.Application.DoEvents()

    For j = 0 To DataGridView2.ColumnCount - 1
        For k As Integer = 1 To DataGridView2.Columns.Count
            xlWorkSheet.Cells(i + 1, j + 1) = DataGridView2(j, i).Value
        Next
    Next
Next