ASHX 生成excel文件

本文介绍了一种使用C#从Web服务导出带有会话信息的Excel报告的方法,并详细展示了如何设置HTTP响应头来实现Excel文件的下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private void GetCandidateExcelConverter(HttpContext context)
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;

// Workbook excelWorkbook = new Workbook();
string originalFile = context.Server.MapPath("~/webservice/report.xlsx");

Workbook excelWorkbook = new Workbook(originalFile);

filename = string.Format("report_{0}_{1:yyyyMMddHHmmss}.xls", context.Session["Name"], DateTime.Now);
LoadDataToCandidateExcel(context, excelWorkbook);

#region downlload excel
string exportFile = context.Server.MapPath("~/output/" + filename);
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.Expires = 1;
HttpContext.Current.Response.ExpiresAbsolute = System.DateTime.Now.AddMinutes(-1);
HttpContext.Current.Response.CacheControl = "Private";
HttpContext.Current.Response.AddHeader("pragma", "no-cache");
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
HttpContext.Current.Response.Charset = String.Empty;
byte[] fileData = excelWorkbook.SaveToStream().ToArray();
context.Response.OutputStream.Write(fileData, 0, fileData.Length);
context.Response.End();
System.IO.MemoryStream ms = new System.IO.MemoryStream(fileData);
Int64 dataToRead = fileData.Length;
int length = 0;
try
{
while (dataToRead > 0)
{
if (HttpContext.Current.Response.IsClientConnected)
{
byte[] buffer = new byte[10000];
length = ms.Read(buffer, 0, 10000);
HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
HttpContext.Current.Response.Flush();
dataToRead = dataToRead - length;
}
else
{
dataToRead = 1;
}
}
}
finally
{
if (ms == null)
ms.Close();
}
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
#endregion
}

转载于:https://www.cnblogs.com/veigd/archive/2013/01/11/2856532.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值