c# webApi返回Excel数据流 || 使用Excel数据流的方式下载Excel

背景:

  在前端无法生成特殊的excel表格,或操作复杂的时候会通过后台进行生成excel。但是服务器的资源也非常宝贵,所以通过数据流的方式就可以实现:不在服务器存储的情况下,使前端成功下载excel文件;

效果如下:

 

 

代码如下:

  1,封装的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/// <summary>
/// 导出excel模板
/// </summary>
/// <returns></returns>
public static byte[] OutputExcel()
{
    try
    {
        NPOI.SS.UserModel.IWorkbook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();
        NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet("sheet");
        IRow Title = sheet.CreateRow(0);
        for (int i = 0; i < 51; i++)
        {
            Title.CreateCell(i).SetCellValue("title" + i);
        }
        byte[] buffer = new byte[1024 * 5];
        using (MemoryStream ms = new MemoryStream())
        {
            workbook.Write(ms, false);
            //ms.Flush();
            //ms.Position=0;
            buffer = ms.ToArray();
            ms.Close();
        }
        return buffer;
    }
    catch (Exception ex)
    {
        return null;
    }
}

  2,控制器方法:

1
2
3
4
5
6
[HttpGet(Name = "Test")]
public FileResult Test()
{           
    var result = ExcelHelper.OutputExcel();
    return File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "UploadTemplate.xlsx");
}

 

posted @   黄金程序员  阅读(2055)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
点击右上角即可分享
微信分享提示