程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> 將DataGrid中數據倒出Excel文件並下載

將DataGrid中數據倒出Excel文件並下載

編輯:.NET實例教程
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 
   
  
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved