2009-09-15 92 views
1

這些例程(vb.net)允許您將gridview轉儲爲CSV,即使單元中存在模板控件。它的工作原理,但我並不滿意。重構: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 
+0

btw,如何讓SO編輯器識別返回t.Replace(「 」,「」)? – BenB 2009-09-15 02:13:36

回答

1
  • 如果你要擔心其他反向轉義HTML文本除了非換空間?您可以使用HttpUtility.HtmlDecode
  • 您的CsvFormatted例程可以對空輸入字符串guard - 它幾乎沒有成本是安全的。
  • 你需要通過Turkey test?有些國家使用分號作爲CSV分隔符。您可能還需要將點或逗號作爲小數分隔符。
  • 我可能會將發出的HttpContext響應中的CSV字符串分離爲單獨的函數。
  • 我可能會使用vbCrLf而不是vbCr & vbLf。

我的主要建議是:創建一些良好的單元測試,確保代碼通過,然後忘記它,然後繼續實現一些更多的功能。代碼封裝得很好,所以如果你決定必要的話,你可以很容易地重構。

+0

偉大的建議,謝謝。火雞測試非常有趣... – BenB 2009-09-16 12:30:26