Code
private void Button1_Click(object sender, System.EventArgs e)
{
// 导出Excel
Response.Clear();
Response.Buffer = true;
Response.AppendHeader("Content-Disposition","attachment;filename=当月工程量统计表.xls"); //定义输出文件和文件名
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
this.EnableViewState = false;
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
//this.SpanProjInfo.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
//---------------------------
System.Web.HttpResponse httpResponse = Page.Response;
httpResponse.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(this.hid_reportname.Value,System.Text.Encoding.UTF8) + DateTime.Now.ToString("yyyyMMdd") + ".xls");
httpResponse.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
httpResponse.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
this.SpanProjInfo.RenderControl(hw);
string filePath2 = Request.PhysicalApplicationPath+"Download\\xx.xls";
System.IO.StreamWriter sw = System.IO.File.CreateText(filePath2);
sw.Write(tw.ToString());
sw.Close();
DownFile(httpResponse,"ttt",filePath2);
httpResponse.End();
}
private void btnExcel_ServerClick(object sender, System.EventArgs e)
{
// 导出Excel
Response.Clear();
Response.Buffer = true;
Response.AppendHeader("Content-Disposition","attachment;filename="+this.hid_reportname.Value); //定义输出文件和文件名
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
this.EnableViewState = false;
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
//this.SpanProjInfo.RenderControl(htw);
Response.Write(SpanProjInfo.InnerHtml.ToString());
Response.End();
}
public 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) + DateTime.Now.ToString("yyyyMMdd") + ".xls;charset=GB2312");
System.IO.FileStream fs= System.IO.File.OpenRead(fullPath);
long fLen=fs.Length;
int size=102400;//每100K同时下载数据
byte[] readData = 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 = 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;
}
}