当它被击中我试图导出到excel按钮我想要调用此api并下载excel表。
我的控制器代码看起来像这样,我老实说卡住,因为我不确定我应该返回什么。我是.net核心api的新手抱歉
[Route("api/excel")]
public class ExportToExcel : Controller
{
private readonly ScadaContext _context;
public ExportToExcel(ScadaContext context)
{
_context = context;
}
// GET: api/values
[HttpGet]
public ActionResult GetExcelMainView()
{
var query = _context.Main_View.Where(x => !x.MeterId.StartsWith("HOGC"));
List<Object[]> MainViewList = new List<Object[]>();
foreach(var p in query)
{
MainViewList.Add(new Object[] { "Battery Voltage", p.BatteryVoltage });
}
MemoryStream stream = new MemoryStream();
using (ExcelPackage pck = new ExcelPackage(stream))
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("MainView");
ws.Cells["A1"].LoadFromArrays(MainViewList);
Response.Clear();
Response.Headers.Add("content-disposition", "attachment; filename=Clients.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var bytes = pck.GetAsByteArray();
Response.Body.WriteAsync(bytes, 0, bytes.Length);
}
}
}
使用FileResult子类之一的最简单方法,例如FileStreamResult
控制器方法File(stream,...,...)为您做到:
return File(stream, contentTypeString, willbeSavedWithThisFileName);
应该工作。我不确定你是否必须再次将你的包重新包装在内存流中
var streamagain = new MemoryStream(package.GetAsByteArray());
(使用您已编写的“手动”代码,我会尝试使用return StatusCode(200)
作为将内容恢复到客户端的方式)。