中国IT动力,最新最全的IT技术教程
最新100篇 | 推荐100篇 | 专题100篇 | 排行榜 | 搜索 | 在线API文档
首 页 | 程序开发 | 操作系统 | 软件应用 | 图形图象 | 网络应用 | 精文荟萃 | 教育认证 | 硬件维护 | 未整理篇 | 站长教程
ASP JS PHP工程 ASP.NET 网站建设 UML J2EESUN .NET VC VB VFP 网络维护 数据库 DB2 SQL2000 Oracle Mysql
服务器 Win2000 Office C DreamWeaver FireWorks Flash PhotoShop 上网宝典 CorelDraw 协议大全 网络安全 微软认证
硬件维护  CPU  主板  硬盘  内存  显卡  显示器  键盘鼠标  声卡音箱  打印机  机箱电源  BIOS  网卡  C#  Java  Delphi  vs.net2005
  当前位置:> 程序开发 > Web开发 > .NET > ASP.NET
将DataGrid中数据倒出Excel文件并下载
作者:未知 时间:2003-01-14 12:12 出处:互联网 责编:chinaitpower
              摘要:暂无

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

关闭本页
 
首页 | 投资与合作 | 服务条款 | 隐私政策 | 收藏本站 | 设为首页 | 新用户注册 | 免责声明 | 使用帮助
Copyright ©2005-2008 chinaitpower.com All rights reserved. www.chinaitpower.com 版权所有