ASHX 生成excel文件

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
}

posted on 2013-01-11 15:34  沸石  阅读(4125)  评论(0编辑  收藏  举报

导航