public bool LendOutExcel(string strFileName, DataTable DT)
{
try
{
//清除Response缓存内容
HttpContext.Current.Response.Clear();
//缓存输出,并在完成整个响应之后将其发送
HttpContext.Current.Response.Buffer = true;
//strFileName指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt .htm
strFileName = strFileName + ".xls";
//设置输出流的HTPP字符集,确定字符的编码格式
//HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
//下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName));
//Response.ContentType指定文件类型.可以为application/ms-excel,application/ms-word,application/ms-txt,application/ms-html或其他浏览器可直接支持文档
HttpContext.Current.Response.ContentType = "application/ms-excel";
string colHeaders = "", ls_item = "";
int i = 0;
//定义表对象与行对像,同时用DataSet对其值进行初始化
DataRow[] myRow = DT.Select("");
//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
for (i = 0; i < DT.Columns.Count - 1; i++)
{
colHeaders += DT.Columns[i].Caption.ToString() + "\t";
}
colHeaders += DT.Columns[i].Caption.ToString() + "\n";
//向HTTP输出流中写入取得的数据信息
HttpContext.Current.Response.Write(colHeaders);
//逐行处理数据
foreach (DataRow row in myRow)
{
//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n
for (i = 0; i < DT.Columns.Count - 1; i++)
ls_item += row[i].ToString() + "\t";
ls_item += row[i].ToString() + "\n";
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
HttpContext.Current.Response.Write(ls_item);
ls_item = "";
}
//写缓冲区中的数据到HTTP头文件中
HttpContext.Current.Response.End();
return true;
}
catch
{
return false;
}
}
原文地址:http://www.cnblogs.com/yuzk/p/3835972.html