我正在使用类 GridViewExportUtil 将 GridView (gvMuster) 导出到 Excel 文件。这工作正常,但是我希望能够向生成的 Excel 文件添加标题(或某种形式的标题等),但我不确定如何执行此操作。
Gridview 通过单击按钮传递给类,如下所示: -
GridViewExportUtil.ExportToFile(("\\somepath\Muster\Muster.xls"), gvMuster)
课程内容如下:-
Public Shared Sub Export(fileName As String, gv As GridView)
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName))
HttpContext.Current.Response.ContentType = "application/ms-excel"
Using sw As New StringWriter()
Export(sw, gv)
HttpContext.Current.Response.Write(sw.ToString())
HttpContext.Current.Response.[End]()
End Using
End Sub
Public Shared Sub ExportToFile(fileName As String, gv As GridView)
Using streamWriter As New StreamWriter(fileName)
Using sw As New StringWriter()
Export(sw, gv)
streamWriter.Write(sw.ToString())
End Using
End Using
End Sub
Public Shared Sub Export(sw As StringWriter, gv As GridView)
Using htw As New HtmlTextWriter(sw)
Dim table As New Table()
table.GridLines = gv.GridLines
If gv.HeaderRow IsNot Nothing Then
GridViewExportUtil.PrepareControlForExport(gv.HeaderRow)
table.Rows.Add(gv.HeaderRow)
End If
For Each row As GridViewRow In gv.Rows
GridViewExportUtil.PrepareControlForExport(row)
table.Rows.Add(row)
Next
If gv.FooterRow IsNot Nothing Then
GridViewExportUtil.PrepareControlForExport(gv.FooterRow)
table.Rows.Add(gv.FooterRow)
End If
table.RenderControl(htw)
End Using
End Sub
Private Shared Sub PrepareControlForExport(ByVal control As Control)
Dim i As Integer = 0
Do While (i < control.Controls.Count)
Dim current As Control = control.Controls(i)
If (TypeOf current Is LinkButton) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text))
ElseIf (TypeOf current Is ImageButton) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText))
ElseIf (TypeOf current Is HyperLink) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text))
ElseIf (TypeOf current Is DropDownList) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text))
ElseIf (TypeOf current Is CheckBox) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked))
End If
If current.HasControls Then
GridViewExportUtil.PrepareControlForExport(current)
End If
i = (i + 1)
Loop
End Sub