可以通过以下步骤实现:
SaveAs
方法或者流的方式保存。Response.ContentType
设置为"application/vnd.ms-excel",并使用Response.AddHeader
设置"Content-Disposition"为"attachment; filename=filename.xlsx",其中filename为下载文件的名称。Response.TransmitFile
或者将文件流写入Response.OutputStream
。以下是一个示例代码:
using System;
using System.IO;
using System.Web;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
public class ExcelDownloadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// 创建工作簿和工作表
IWorkbook workbook = new XSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet1");
// 添加表头
IRow headerRow = sheet.CreateRow(0);
headerRow.CreateCell(0).SetCellValue("Column1");
headerRow.CreateCell(1).SetCellValue("Column2");
// 添加数据行
IRow dataRow = sheet.CreateRow(1);
dataRow.CreateCell(0).SetCellValue("Data1");
dataRow.CreateCell(1).SetCellValue("Data2");
// 保存Excel文件到服务器临时目录
string tempFilePath = Path.Combine(Path.GetTempPath(), "temp.xlsx");
using (FileStream fs = new FileStream(tempFilePath, FileMode.Create))
{
workbook.Write(fs);
}
// 设置HTTP响应头,指定下载文件的类型和名称
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AddHeader("Content-Disposition", "attachment; filename=excel.xlsx");
// 将Excel文件发送给客户端
context.Response.TransmitFile(tempFilePath);
context.Response.Flush();
// 删除临时文件
File.Delete(tempFilePath);
}
public bool IsReusable
{
get { return false; }
}
}
在上述示例代码中,使用了NPOI库来生成Excel文件,并通过HttpContext
对象来处理HTTP请求和响应。生成的Excel文件保存在服务器的临时目录中,并通过HTTP响应发送给客户端进行下载。
领取专属 10元无门槛券
手把手带您无忧上云