0

我一直在尝试将 Silverlight 中的一些数据网格导出到 excel 中,但到目前为止还没有成功。所以现在我只是想让它们导出为 csv 文件,然后可以在 excel 中打开。我创建了一个类来导出数据网格,它确实导出并保存了一个 csv 文件。但是,csv 文件不包含任何数据。

Imports System.IO

Public Class clsExportData
   'Public Shared Sub Export(dg As DataGrid)
   '    SaveExportedGrid(ExportDataGrid(True, dg))
   'End Sub


Public Shared Sub Export(dg As DataGrid, withHeaders As Boolean)
    SaveExportedGrid(ExportDataGrid(withHeaders, dg))
End Sub

Private Shared Sub SaveExportedGrid(data As String)
    Dim sfd As New SaveFileDialog()
    sfd.DefaultExt = "csv"
    sfd.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*"
    sfd.FilterIndex = 1

    If If(sfd.ShowDialog(), False) Then
        Using sr As New StreamWriter(sfd.OpenFile())
            sr.Write(data)
        End Using
    End If
End Sub

Private Shared Function ExportDataGrid(withHeaders As Boolean, grid As DataGrid) As String
    Dim colPath As String
    Dim propInfo As System.Reflection.PropertyInfo
    Dim binding As System.Windows.Data.Binding
    Dim strBuilder As New System.Text.StringBuilder()
    Dim source As System.Collections.IList = TryCast(grid.ItemsSource, System.Collections.IList)
    If source Is Nothing Then
        Return ""
    End If

    Dim headers As New List(Of String)()
    grid.Columns.ToList().ForEach(Function(col)
                                      If TypeOf col Is DataGridBoundColumn Then
                                          headers.Add(FormatCSVField(col.Header.ToString()))
                                      End If

                                  End Function)
    strBuilder.Append([String].Join(",", headers.ToArray())).Append(vbCr & vbLf)

    For Each data As [Object] In source
        Dim csvRow As New List(Of String)()
        For Each col As DataGridColumn In grid.Columns
            If TypeOf col Is DataGridBoundColumn Then
                binding = TryCast(col, DataGridBoundColumn).Binding
                colPath = binding.Path.Path
                propInfo = data.[GetType]().GetProperty(colPath)
                If propInfo IsNot Nothing Then
                    csvRow.Add(FormatCSVField(propInfo.GetValue(data, Nothing).ToString()))
                End If
            End If
        Next
        strBuilder.Append([String].Join(",", csvRow.ToArray())).Append(vbCr & vbLf)
    Next

    Return strBuilder.ToString()
End Function

Private Shared Function FormatCSVField(data As String) As String
    Return [String].Format("""{0}""", data.Replace("""", """""""").Replace(vbLf, "").Replace(vbCr, ""))
End Function

结束类

4

1 回答 1

1

请尝试以下操作

Dim source As System.Collections.IEnumerable = TryCast(grid.ItemsSource, System.Collections.IEnumerable)
If source Is Nothing Then
    Return ""
End If

此外,请确保您使用调试器单步执行您的代码,并查看它失败的地方。

于 2012-05-06T06:42:28.520 回答