重构:Gridview导出到CSV文件

时间:2009-09-15 02:12:08

标签: asp.net vb.net gridview refactoring

这些例程(vb.net)允许您将gridview转储为CSV,即使单元格中有模板化控件也是如此。它有效,但我对此并不感到兴奋。

我应该做些什么改进?为什么?

Private Shared Function CsvFormatted(ByVal t As String) As String
    If t.Contains(",") Then
        t = """" + t + """"
    End If
    Return t.Replace("\ ", "")

End Function

Private Shared Function GetCellText(ByVal cell As DataControlFieldCell) As String
    If cell.Controls.Count = 0 Then
        Return CsvFormatted(cell.Text)
    Else
        For Each current In cell.Controls
            If TypeOf current Is Label Then
                Return CsvFormatted(TryCast(current, Label).Text)
            ElseIf TypeOf current Is TextBox Then
                Return CsvFormatted(TryCast(current, TextBox).Text)
            ElseIf TypeOf current Is LinkButton Then
                Return CsvFormatted(TryCast(current, LinkButton).Text)
            ElseIf TypeOf current Is ImageButton Then
                Return CsvFormatted(TryCast(current, ImageButton).AlternateText)
            ElseIf TypeOf current Is HyperLink Then
                Return CsvFormatted(TryCast(current, HyperLink).Text)
            ElseIf TypeOf current Is DropDownList Then
                Return CsvFormatted(TryCast(current, DropDownList).SelectedItem.Text)
            ElseIf TypeOf current Is CheckBox Then
                Return CsvFormatted(If(TryCast(current, CheckBox).Checked, "True", "False"))
            End If
        Next
    End If
    Return ""
End Function

Public Shared Sub ExportGridViewToCSV(ByVal grid As GridView, ByVal fileName As String)
    HttpContext.Current.Response.Clear()
    HttpContext.Current.Response.Buffer = True
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName)
    HttpContext.Current.Response.Charset = ""
    HttpContext.Current.Response.ContentType = "application/text"
    Dim sb As New StringBuilder()
    For k As Integer = 0 To grid.Columns.Count - 1
        grid.Columns(k).Visible = True
        'add separator
        sb.Append(grid.Columns(k).HeaderText + ","c)
    Next
    'append new line
    sb.Append(vbCr & vbLf)
    For i As Integer = 0 To grid.Rows.Count - 1
        For k As Integer = 0 To grid.Columns.Count - 1
            grid.Columns(k).Visible = True
            'add separator
            sb.Append(GetCellText(grid.Rows(i).Cells(k)) + ","c)
        Next
        'append new line
        sb.Append(vbCr & vbLf)
    Next
    HttpContext.Current.Response.Output.Write(sb.ToString())
    HttpContext.Current.Response.Flush()
    HttpContext.Current.Response.End()
End Sub

1 个答案:

答案 0 :(得分:1)

  • 除了不间断的空间之外,你是否应该担心其他HTML文字?您可以使用HttpUtility.HtmlDecode
  • 您的CsvFormatted例程可以guard对空输入字符串 - 几乎没有任何安全措施。
  • 你需要通过Turkey test吗?某些国家/地区使用分号作为CSV分隔符。您可能还需要将点或逗号视为十进制分隔符。
  • 我可能会将CSV字符串构建为单独的函数,而不是发出HttpContext响应。
  • 我可能会使用vbCrLf而不是vbCr& vbLf。

我的主要建议:创建一些好的单元测试,确保代码通过,然后忘记它,然后继续实现更多功能。代码封装得相当好,所以如果您认为有必要,可以在以后轻松进行重构。