【#文档大全网# 导语】以下是®文档大全网的小编为您整理的《C#内存流输出excel文件下载》,欢迎阅读!
using System;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
using System.Web;
public partial class Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//调用函数,创建excel工作簿
HSSFWorkbook hssfWorkbook = CreateWorkBook();
//下载文件
DownLoad(hssfWorkbook,"导出Excel文件");
}
#region 创建excel工作簿
/// <summary>
/// 创建excel工作簿
/// </summary>
/// <returns></returns>
private HSSFWorkbook CreateWorkBook()
{
//创建工作簿
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
//创建工作表,名为sheet1
ISheet sheet = hssfWorkbook.CreateSheet("sheet1");
//创建行
IRow row = sheet.CreateRow(0);
//创建单元格
ICell cell = row.CreateCell(0);
//设置单元格值类型
cell.SetCellType(CellType.STRING);
//设置单元格值
cell.SetCellValue("hello world");
//返回工作簿
return hssfWorkbook;
}
#endregion
#region 输出到下载文件
/// <summary>
/// 下载文件
/// </summary>
/// <param name="hssfWorkbook">excel工作簿</param>
/// <param name="fileName">文件名</param>
private void DownLoad(HSSFWorkbook hssfWorkbook, string fileName)
{
using (MemoryStream memoryStram = new MemoryStream())
{
//把工作簿写入到内存流中
hssfWorkbook.Write(memoryStram);
//设置输出编码格式
Response.ContentEncoding = System.Text.Encoding.UTF8;
//设置输出流
Response.ContentType = "application/octet-stream";
//防止中文乱码
fileName = HttpUtility.UrlEncode(fileName);
//设置输出文件名
Response.AppendHeader("Content-Disposition", ""attachment; filename=" + fileName + ".xls");
//输出
Response.BinaryWrite(memoryStram.GetBuffer());
}
}
#endregion
}
本文来源:https://www.wddqxz.cn/702a7908a6e9856a561252d380eb6294dd882215.html