程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> DataTable數據導出成Excel文件的小例子

DataTable數據導出成Excel文件的小例子

編輯:ASP.NET基礎

復制代碼 代碼如下:
///
/// 將DataTable中的數據導出到指定的Excel文件中
///
/// Web頁面對象
/// 包含被導出數據的DataTable對象
/// Excel文件的名稱
public static void Export(System.Web.UI.Page page,System.Data.DataTable tab,string FileName)
{
System.Web.HttpResponse httpResponse = page.Response;
System.Web.UI.WebControls.DataGrid dataGrid=new System.Web.UI.WebControls.DataGrid();
dataGrid.DataSource=tab.DefaultView;
dataGrid.AllowPaging = false;
dataGrid.HeaderStyle.BackColor = System.Drawing.Color.Green;
dataGrid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
dataGrid.HeaderStyle.Font.Bold = true;
dataGrid.DataBind();
httpResponse.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(FileName,System.Text.Encoding.UTF8)); //filename="*.xls";
httpResponse.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
httpResponse.ContentType ="application/ms-excel";
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
dataGrid.RenderControl(hw);

string filePath = page.Server.MapPath("..")+"//Files//" +FileName;
System.IO.StreamWriter sw = System.IO.File.CreateText(filePath);
sw.Write(tw.ToString());
sw.Close();

DownFile(httpResponse,FileName,filePath);

httpResponse.End();
}
private static bool DownFile(System.Web.HttpResponse Response,string fileName,string fullPath)
{
try
{
Response.ContentType = "application/octet-stream";

Response.AppendHeader("Content-Disposition","attachment;filename=" +
HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8) + ";charset=GB2312");
System.IO.FileStream fs= System.IO.File.OpenRead(fullPath);
long fLen=fs.Length;
int size=102400;//每100K同時下載數據
byte[] readData = http://www.jb51.net/yongle_tianya/archive/2011/10/24/new byte[size];//指定緩沖區的大小
if(size>fLen)size=Convert.ToInt32(fLen);
long fPos=0;
bool isEnd=false;
while (!isEnd)
{
if((fPos+size)>fLen)
{
size=Convert.ToInt32(fLen-fPos);
readData = http://www.jb51.net/yongle_tianya/archive/2011/10/24/new byte[size];
isEnd=true;
}
fs.Read(readData, 0, size);//讀入一個壓縮塊
Response.BinaryWrite(readData);
fPos+=size;
}
fs.Close();
System.IO.File.Delete(fullPath);
return true;
}
catch
{
return false;
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved