前言

产品经理有一个需求,就是将cosmosDB里的数据,导出到Excel中.

1.新建一个.net core web api controller

添加引用:EPPlus.Core

 Install-Package EPPlus.Core

命名空间:

using OfficeOpenXml;

2.在HomeController里添加Export的方法

这里会遇到几个坑:

第一个是使用HttpResponseMessage的时候,返回的不是一个文件,而是一个HttpResponseMessage 类型的json;

第二个是 返回的File的时候,注意要加上stream.position=0;

第三个是将stream保存在内存(小文件),有些虚机不一定有C盘,所以创建物理路径是存在risk,暂存在内存避免crash。要是大文件还是另寻他法,万一out of memory。

这里我们使用IActionResult返回类型。

    [HttpGet]
[Route("export")]
public async Task<IActionResult> Export()
{
string fileName = $"{Guid.NewGuid().ToString()}.xlsx"; //store in memory rather than pysical directory
var stream = new MemoryStream();
var messages = await ConversationManager.GetConversationMessagesAsync();
var columns = new ConversationMessage();
using (ExcelPackage package = new ExcelPackage(stream))
{
// add worksheet
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Conversation Message");
//add head
worksheet.Cells[1, 1].Value = "From Id";
worksheet.Cells[1, 2].Value = "To Id";
worksheet.Cells[1, 3].Value = "Message";
worksheet.Cells[1, 4].Value = "Time";
worksheet.Cells[1, 5].Value = "Attachment";
worksheet.Cells[1, 6].Value = "Conversation Id"; //add value
var rowNum = 2; // rowNum 1 is head
foreach (var message in messages)
{
worksheet.Cells["A" + rowNum].Value = message.FromId;
worksheet.Cells["B" + rowNum].Value = message.ToId;
worksheet.Cells["C" + rowNum].Value = message.Message;
worksheet.Cells["D" + rowNum].Value = message.MsgTime;
worksheet.Cells["E" + rowNum].Value = message.Attachment;
worksheet.Cells["F" + rowNum].Value = message.ConversationId;
rowNum++;
}
package.Save();
}
stream.Position = 0;
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
}

3.说明

最后在浏览器打开api,成功下载:



这里highlighted的部分就是代码中的Worksheets,还可以对表头进行加粗上色之类的,暂时没有这个需求就不深入了。

一开始使用如下方式:

[HttpGet]
public HttpResponseMessage DownloadFile(string fileName)
{
if (!string.IsNullOrEmpty(fileName))
{
string filePath = "/images/";
string fullPath = AppDomain.CurrentDomain.BaseDirectory + filePath + "/" + fileName;
if (File.Exists(fullPath))
{ HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
var fileStream = new FileStream(fullPath, FileMode.Open);
response.Content = new StreamContent(fileStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
return response;
}
} return new HttpResponseMessage(HttpStatusCode.NotFound);
}

ContentDisposition会出现为null的情况,就没有FileName,所以这一步就已经exception了。

但貌似并不能成功下载(打开api,直接下载并显示在浏览器下方)

.Net core Web API导出数据到Excel的更多相关文章

  1. ASP.NET Core Web API 如何 数据分页 以及遇到'OFFSET' 附近有语法错误

    最近领导叫我做的一个B/S端的小项目,突发奇想想用到core web api 今天写数据分页的时候,就想着 用linq分页查询吧,直接上代码 _context.Skip(Size * (PageNum ...

  2. 使用 ASP.NET Core MVC 创建 Web API——响应数据的内容协商(七)

    使用 ASP.NET Core MVC 创建 Web API 使用 ASP.NET Core MVC 创建 Web API(一) 使用 ASP.NET Core MVC 创建 Web API(二) 使 ...

  3. .net core web api 与httpclient发送和接收文件及数据

    客户端 HttpClient var url = $"https://localhost:44323/api/values/posttest?resource_source=yangwwme ...

  4. List多个字段标识过滤 IIS发布.net core mvc web站点 ASP.NET Core 实战:构建带有版本控制的 API 接口 ASP.NET Core 实战:使用 ASP.NET Core Web API 和 Vue.js 搭建前后端分离项目 Using AutoFac

    List多个字段标识过滤 class Program{  public static void Main(string[] args) { List<T> list = new List& ...

  5. ASP.NET Core WEB API 使用element-ui文件上传组件el-upload执行手动文件文件,并在文件上传后清空文件

    前言: 从开始学习Vue到使用element-ui-admin已经有将近快两年的时间了,在之前的开发中使用element-ui上传组件el-upload都是直接使用文件选取后立即选择上传,今天刚好做了 ...

  6. 加快ASP。NET Core WEB API应用程序。第2部分

    下载source from GitHub 使用各种方法来增加ASP.NET Core WEB API应用程序的生产力 介绍 第1部分.创建测试RESTful WEB API应用程序第2部分.增加了AS ...

  7. 导出数据到Excel --使用ExcelReport有感

    先看图,这是几个月前用NPOI写的导出数据到Excel,用了上百行代码,而且难控制,导出来也比较难看 excel打开的效果 下面是我用ExcelReport类库导出到Excel的操作 1.首先引用Ex ...

  8. ASP.NET Core Web API Cassandra CRUD 操作

    在本文中,我们将创建一个简单的 Web API 来实现对一个 “todo” 列表的 CRUD 操作,使用 Apache Cassandra 来存储数据,在这里不会创建 UI ,Web API 的测试将 ...

  9. 在Mac下创建ASP.NET Core Web API

    在Mac下创建ASP.NET Core Web API 这系列文章是参考了.NET Core文档和源码,可能有人要问,直接看官方的英文文档不就可以了吗,为什么还要写这些文章呢? 原因如下: 官方文档涉 ...

随机推荐

  1. Ubuntu14.04安装androidStudio错误解除

    错误1 ubuntu androidStudio :app:mergeDebugResources FAILED 办法: sudo dpkg --add-architecture i386 sudo ...

  2. LeetCode(49)-Valid Parentheses

    题目: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the ...

  3. java finalize方法总结、GC执行finalize的过程

    注:本文的目的并不是鼓励使用finalize方法,而是大致理清其作用.问题以及GC执行finalize的过程. 1. finalize的作用 finalize()是Object的protected方法 ...

  4. angular1.0 app

    angular 1.0 简单的说一下就是ng启动阶段是 config-->run-->compile/link config阶段是给了ng上下文一个针对constant与provider修 ...

  5. 跨JavaScript对象作用域调用setInterval方法

    跨JavaScript对象作用域调用setInterval方法: var id = window.setInterval(function() {foofunc.call(this);}, 200);

  6. java中Scanner类nextLine()和next()的区别和使用方法

    转载:http://blog.csdn.net/zhiyuan_ma/article/details/51592730 在实现字符窗口的输入时,很多人更喜欢选择使用扫描器Scanner,它操作起来比较 ...

  7. storm中的Scheduler

    Scheduler是storm的调度器,负责为topology分配当前集群中可用的资源.Storm分别提供了3中调度器: EvenScheduler:会将系统中的可用资源均匀地分配给当前需要任务分配的 ...

  8. 分布式文件系统MFS、Ceph、GlusterFS、Lustre的比较

    原文:http://blog.csdn.net/metaxen/article/details/7108958 MooseFS(MFS) Ceph GlusterFS Lustre Metadata ...

  9. git push The requested URL returned error: 403 Forbidden while accessing

    错误提示信息: error: The requested URL returned error: Forbidden while accessing https://github.com/xingfu ...

  10. JavaScript高级程序设计(二)

    一.函数 1.1 JS中函数无重载,同一作用域下定义两个函数,而不会引发错误,但真正调用的是后面定义的函数.例如: function doAdd(iNum){ alert(iNum+100); } f ...