首页 文章

将数据从GridView导出到Excel的有效方法是什么? [关闭]

提问于
浏览
-1

我测试了几个VB代码示例,将数据从GridView导出到Excel . 一切都太慢而不实用 . 我在GridView中处理200k行或更多行 . 一切都从SQL Server加载到GridView非常快,但是从GridView到Excel的速度非常慢 . 我想知道是否有一种快速的方法将数据移动到Excel中,比如将所有内容加载到数组中,而不是循环遍历200k行数据 .

或者,我可以写入CSV,然后在Excel中打开它吗?如果这很快,那对我来说肯定是一个选择 .

感谢您分享您的智慧专家 .

1 回答

  • 1

    我认为CSV是最快的,但 Excel.Range.Value2 允许您发送一个数组,而不是一次填充一个单元格:

    Dim xl As New Excel.Application 'always use a variable to reference Excel, otherwise it may stay in memory, hidden.'
    Dim b As Excel.Workbook = xl.Workbooks.Add 'do not use b = New Excel.Workbook, as this can cause a memory leak'
    Dim s As Excel.Worksheet
    
    xl.Visible = True
    Dim sLast As Excel.Worksheet = b.Worksheets(b.Worksheets.Count)
    b.Worksheets.Add(, sLast)
    s = b.Worksheets(1) '1-based'
    Dim o(199999, 1) As Object
    For i As Integer = 0 To 199999
      o(i, 0) = i.ToString
      o(i, 1) = (200000 - i).ToString
    Next i
    s.Name = "ExcelDemo"
    Dim r As Excel.Range = s.Range("A1", "B200000")
    r.Value2 = o
    s.Activate()
    Dim strFilename As String = My.Computer.FileSystem.SpecialDirectories.Desktop & "\Junk" 'N.B. extension automatically added'
    b.SaveAs(strFilename)
    strFilename = b.FullName 'get full filename'
    xl.Quit()
    MsgBox(strFilename & " saved")
    

相关问题