【问题标题】:Export to Excel as a response in web API导出到 Excel 作为 Web API 中的响应
【发布时间】:2016-01-28 05:52:42
【问题描述】:

我正在使用 Web API 4.5.1。我在 C# 代码中生成 API 并将这个 API 传递给前端,前端是基于 HTML 和 AngularJS JavaScript 构建的。我的要求是创建一个用于导出到 Excel 到前端的 API。我有点卡在这里。我收到了来自前端人员的来自 fromdate 和 todate 的请求。基于此,我将查询数据库以获取数据,如果成功,则从中获取 HTML 格式。我无法走得更远,因为我是新手。下面是我试图实现这一点的代码:

[HttpPost]
public HttpResponseMessage ExportToExcel(string fromTimeStamp, string toTimeStamp)
{
    DateTime fromDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
    fromDate = fromDate.AddMilliseconds(Convert.ToDouble(fromTimeStamp)).ToLocalTime();
    fromDate.AddDays(1);

    DateTime toDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
    toDate = toDate.AddMilliseconds(Convert.ToDouble(toTimeStamp)).ToLocalTime();
    toDate.AddDays(1);

    var fromDate1 = fromDate.AddDays(1).ToString("yyyy-MM-dd");
    var toDate1 = toDate.AddDays(1).ToString("yyyy-MM-dd");

    var bal = new AdminBAL();
    var ExportData = bal.ExportToExcel(fromDate1, toDate1);
    //where Exportdata is the html format for the data required.
    // unable to find the solution here
}

我怎样才能完成这个操作?

【问题讨论】:

  • 有很多关于 SO 的问题可以帮助您编写 excel 文件,还有一些问题解释了如何通过 Web API 将 excel 文件作为下载发送。寻找这些并尝试将它们组合起来,但不要指望我们为您编写代码。
  • 一个简单的excel库可以在这里找到:epplus.codeplex.com

标签: c# angularjs asp.net-web-api export-to-excel


【解决方案1】:

你可以试试这个吗?

 var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
        //If you have Physical file Read the fileStream and use it.
        response.Content = new StreamContent(fileStream);
        //OR
        //Create a file on the fly and get file data as a byte array and send back to client
        response.Content = new ByteArrayContent(fileBytes);//Use your byte array
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = fileName;//your file Name- text.xls
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/ms-excel");
        //response.Content.Headers.ContentType  = new MediaTypeHeaderValue("application/octet-stream");
        response.Content.Headers.ContentLength = fileStream.Length;
        response.StatusCode = System.Net.HttpStatusCode.OK;

我得到了这个工作正常。如果您对此有任何疑问,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 2019-03-16
    • 2010-11-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多