DataTable數(shù)據(jù)導出成Excel文件的小例子
///
/// 將DataTable中的數(shù)據(jù)導出到指定的Excel文件中
///
/// Web頁面對象
/// 包含被導出數(shù)據(jù)的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("..")+"http://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同時下載數(shù)據(jù)
byte[] readData = http://www.dhdzp.com/yongle_tianya/archive/2011/10/24/new byte[size];//指定緩沖區(qū)的大小
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.dhdzp.com/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;
}
}
相關文章
asp.net 數(shù)據(jù)綁定時對數(shù)據(jù)列做個性化處理
asp.net 數(shù)據(jù)綁定時對數(shù)據(jù)列做個性化處理,需要的朋友可以參考下。2011-12-12
ASP.NET?使用?Dispose?釋放資源的四種方法詳細介紹
本篇文章主要介紹了ASP.NET?使用?Dispose?釋放資源的四種方法,有興趣的同學可以來看看,喜歡的話記得收藏一下哦,方便下次瀏覽觀看2021-11-11
asp.net利用NamingContainer屬性獲取GridView行號的方法
在最近的一個項目中,用到在GridView模板列中添加有DropDownList控件,并開啟其AutoPostback屬性。當發(fā)生SelectedIndexChanged事件時,想同時獲取其所在的行號,從而獲取相應的行信息。2013-07-07
.net生成縮略圖及水印圖片時出現(xiàn)GDI+中發(fā)生一般性錯誤解決方法
這篇文章主要介紹了.net生成縮略圖及水印圖片時出現(xiàn)GDI+中發(fā)生一般性錯誤解決方法 ,需要的朋友可以參考下2014-11-11
asp.net利用cookie保存用戶密碼實現(xiàn)自動登錄的方法
這篇文章主要介紹了asp.net利用cookie保存用戶密碼實現(xiàn)自動登錄的方法,實例分析了asp.net針對cookie的創(chuàng)建、提取與銷毀操作技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-01-01

