Pour the data in DataGrid and download the excel file and download

xiaoxiao2021-03-06  97

Imports system

Imports System.Text

Namespace TOEXCEL

'Features: Generate the DataGrid in ASP.NET to create an Excel file download. 'Mountains improvement: 1, support Chinese 2, hidden columns do not display the' Date: 2002.10.30public Class DataGridtocsv

Public function generatefile (byref page as system.web.ui.page, byval myDataGrid as system.web.ui.webcontrols.datagrid, Byval FileName As String) AS STRING

Dim RespRes Httpresponsedim Colcount As Integer = MyDataGrid.columns.count - 1

Resp = Page.Response

Resp.contentencoding = system.text.encoding.getencoding ("GB2312") 'Resolves Chinese garbled "Resp.Charset =" UTF-8 "' Resp.addFileDependency (filename) 'Resp.contentType =" Text / html "' 'Resp.Appendheader ("Content-Type", "Text / HTML; Charset = GB2312")

Resp.Appendheader ("Content-Disposition", "attachment; filename =" filename) 'necessary, make download files

Dim colheaders as string = "" DIM STRITEMS AS STRINGBUILDER = New StringBuilder ()

DIM Mycol as DataGridColumn

DIM I as integer

For i = 0 to colcountmycol = mydatagrid.columns (i) if mycol.visible = true kilofeaders = colheaders & mycol.Headertext.toString & "End IfNext

IF colheaders.length> 0 thncolheaders = colheaders.substring (0, colheaders.lastindexof (",")) Endiff

Colheaders = colheaders & chr (13) & chr (10)

Resp.write (colheaders)

DIM Colrow As String

DIM ITEM AS DataGridItem

For Each Item in MyDataGrid.ItemsResp.write (formatexportrow (Colcount, Item, MyDataGrid) Next Item

Resp.end ()

END FUNCTION

Private Function FormatExportRow (ByVal colCount As Integer, ByVal Item DataGridItem As, ByVal MyDataGrid As System.Web.UI.WebControls.DataGrid) As StringDim strItem As StringDim i As IntegerFor i = 0 To colCountIf MyDataGrid.Columns (i) .Visible = True Thenif Item.cells (i) .text is system.dbnull.value kil titym.cells (i) .text = "" END IFIF I = Colcount Tenstritem = item.cells (i) .text.toTString & Chr (13) & CHR (10) Elsestritem = item.cells (i) .Text.toString & "," End IFEND IFNextStritem = Replace (strItem, "," ") Return Stritement Function

END CLASS

End Namespace

转载请注明原文地址:https://www.9cbs.com/read-123185.html

New Post(0)