从Web API返回.xlsx excel文件 [英] Return .xlsx excel file from web API

查看:590
本文介绍了从Web API返回.xlsx excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<pre>
Error	CS1503	Argument 1: cannot convert from 'System.Collections.Generic.List<WebApi2.Controllers.Record>' to 'System.IO.Stream'	





我的尝试:





What I have tried:

[HttpGet]
        [Route("ExcelDownload")]
        public HttpResponseMessage ExcelDownload()
        {                       
            var reportStream = RecordInfo();
            var result = Request.CreateResponse(HttpStatusCode.OK);
            result.Content = new StreamContent(reportStream); // Getting error here
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "Report.xlsx"
            };

            return result;
        }


        public List<Record> RecordInfo()
        {
            List<Record> recordobj = new List<Record>();
            recordobj.Add(new Record { FName = "Smith", LName = "Singh", Address = "Knpur" });
            recordobj.Add(new Record { FName = "John", LName = "Kumar", Address = "Lucknow" });
            recordobj.Add(new Record { FName = "Vikram", LName = "Kapoor", Address = "Delhi" });
            recordobj.Add(new Record { FName = "Tanya", LName = "Shrma", Address = "Banaras" });
            recordobj.Add(new Record { FName = "Malini", LName = "Ahuja", Address = "Gujrat" });
            recordobj.Add(new Record { FName = "Varun", LName = "Katiyar", Address = "Rajasthan" });
            recordobj.Add(new Record { FName = "Arun  ", LName = "Singh", Address = "Jaipur" });
            recordobj.Add(new Record { FName = "Ram", LName = "Kapoor", Address = "Panjab" });
            recordobj.Add(new Record { FName = "Vishakha", LName = "Singh", Address = "Banglor" });
            recordobj.Add(new Record { FName = "Tarun", LName = "Singh", Address = "Kannauj" });
            recordobj.Add(new Record { FName = "Mayank", LName = "Dubey", Address = "Farrukhabad" });
            return recordobj;
        }

推荐答案

错误消息告诉您确切的问题是什么,您无法生成将< Record> 列入流对象而不通过转换器。即使你可以输出不是Excel文件。
The error message is telling you exactly what the problem is, you cannot make a List<Record> into a stream object without going through a converter. And even if you could the output is not an Excel file.


这篇关于从Web API返回.xlsx excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆