从数据表快速批量插入到excel

时间:2017-05-14 16:42:09

标签: excel vb.net

从MS SQL表填充数据表后,这是我在excel中显示它的方法。有没有更快的方法呢?

我认为记录集选项:

  

.CopyFromRecordset

更快

    Transform trans = gameObject.GetComponent<Transform>();
    string propertyName = "position";

   trans[propertyName] = new Vector3(0, 0, 0);

2 个答案:

答案 0 :(得分:0)

从SQL DB获取数据到表格的最佳方法是=IMPORTDATA("PUT_LINK_HERE")

答案 1 :(得分:0)

由于您使用的是Excel互操作,因此提高性能的最佳方法是尽量减少互操作调用的次数。将矩形数据块传输到Excel可以通过将二维Object数组分配给相同调整大小的Excel.Range来完成。根据传输的数据量,由于消耗了内存资源,将其作为单个传输或多个块执行可能会更快。

以下代码以行块的形式传输数据,允许您指定每个事务传输的最大行数。

Public Shared Sub ExportDTBlockMode(dt As DataTable, topLeftCell As Excel.Range, Optional maxRowsInBlock As Int32 = 1000)
    Dim calcMode As Excel.XlCalculation = topLeftCell.Application.Calculation
    topLeftCell.Application.Calculation = Excel.XlCalculation.xlCalculationManual

    Dim upperBoundRows As Int32 = Math.Min(dt.Rows.Count + 1, maxRowsInBlock) - 1

    Dim exportArray As Object(,) = New Object(0 To upperBoundRows, 0 To dt.Columns.Count - 1) {}

    Dim exportRange As Excel.Range = CType(topLeftCell.Cells.Item(1, 1), Excel.Range)
    exportRange = exportRange.Resize(upperBoundRows + 1, dt.Columns.Count)

    ' create and export header
    Dim header As New List(Of String)
    Dim colIndex As Int32
    Dim rowIndex As Int32 = 0
    Dim arrayRowIndex As Int32 = 0
    For Each c As DataColumn In dt.Columns
        exportArray(arrayRowIndex, colIndex) = c.ColumnName
        colIndex += 1
    Next

    For Each dr As DataRow In dt.Rows
        arrayRowIndex += 1
        colIndex = 0
        For Each c As DataColumn In dt.Columns
            exportArray(arrayRowIndex, colIndex) = dr.ItemArray(colIndex)
            colIndex += 1
        Next
        If arrayRowIndex = upperBoundRows Then
            exportRange.Value(Excel.XlRangeValueDataType.xlRangeValueDefault) = exportArray
            exportRange = exportRange.Offset(maxRowsInBlock, 0)
            arrayRowIndex = -1
        End If
    Next
    If arrayRowIndex > -1 Then
        Dim exportArrayResized(0 To arrayRowIndex, dt.Columns.Count - 1) As Object
        For r As Int32 = 0 To arrayRowIndex
            For c As Int32 = 0 To dt.Columns.Count - 1
                exportArrayResized(r, c) = exportArray(r, c)
            Next

        Next
        exportRange = exportRange.Resize(arrayRowIndex + 1, dt.Columns.Count)

        exportRange.Value(Excel.XlRangeValueDataType.xlRangeValueDefault) = exportArrayResized
    End If
    topLeftCell.Application.Calculation = calcMode

End Sub
相关问题