嘿,克里斯。我意识到您已经接受了答案,但我想我会发布我使用的解决方案。希望它对某人有用。如果不是,至少它为我在未来某个时候找到它提供了一个地方。:-)
这是直接从 Excel 2007 代码模块触发的 VBA 代码。它可以很容易地转换为.Net。
数据操作的关键是数据透视表对象。我发现它在将数据放入您指定的布局方面非常有效。
Sub GetIndexData ()
Dim cn as ADODB.Connection, cmd As ADODB.Command, rs As ADODB.Recordset
Dim rPivotTopLeft As Range, rPivotBottomRight As Range
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'Get the data.'
Set cn = New ADODB.Connection
With cn
.Provider = "SQLOLEDB"
.ConnectionString = "Database=" & mDBName & ";" & _
"Server=" & mDBServerName & ";" & _
"UID=" & mDBUserID & ";" & _
"Password=" & mDBPassword & ";" & _
"Persist Security Info=True;"
.CursorLocation = adUseClient
.Open
End With
Set cmd = New ADODB.Command
Set rs = New ADODB.Recordset
With cmd
.ActiveConnection = adoTools.DBConnection
.CommandType = adCmdText
.CommandText = "SELECT YourData From YourSource WHERE YourCritera"
Set rs = .Execute
End With
If Not (rs.BOF And rs.EOF) Then 'Check that we have some data.'
'Put the data into a worksheet.'
With wsRawData
.Cells.CurrentRegion.Clear
Set rPivotTopLeft = .Range("A1")
With ThisWorkbook.PivotCaches.Add(SourceType:=xlExternal)
Set .Recordset = rs
.CreatePivotTable _
TableDestination:=rPivotTopLeft, _
TableName:="MyPivotTable"
End With
'Massage the data into the desired layout.'
With .PivotTables("MyPivotTable")
.ManualUpdate = True
.PivotFields("Date").Orientation = xlRowField
.PivotFields("Index").Orientation = xlColumnField
.AddDataField .PivotFields("Return"), "Returns", xlSum
.DisplayFieldCaptions = False
.ColumnGrand = False
.RowGrand = False
.ManualUpdate = False
End With
mMonthCount = Range(.Range("A3"), .Cells(Rows.Count, "A").End(xlUp)).Count
mIndexCount = Range(.Range("B2"), .Cells(2, Columns.Count).End(xlToLeft)).Count
'Convert pivot table to values.'
Set rPivotBottomRight = .Cells(mMonthCount + 2, mIndexCount + 1)
With .Range(rPivotTopLeft, rPivotBottomRight)
.Copy
.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End With
'Format the worksheet.'
.Range("A3").Resize(mMonthCount, 1).NumberFormat = "mmm-yy"
.Range("B3").Resize(mMonthCount, mIndexCount).NumberFormat = "0.00%"
Union(.Rows(2), .Columns(1)).Font.Bold = True
.Cells.ColumnWidth = 7.14
.Rows(1).Delete
End With
rs.close
Set rs = Nothing
cmd.ActiveConnection = Nothing
Set cmd = Nothing
cn.close
Set cn = Nothing
End Sub
从那里可以相对容易地利用内置的 excel 回归统计来输出相关矩阵。使用这种技术,我将在大约 45 秒内生成一个具有 600x600 相关矩阵的工作表。
请注意,应更改 .PivotFields 参数以适合数据源中数据的列名。