我正在使用 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
}
如何完成这个操作?
请您参考如下方法:
你能试试这个吗?
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;
我得到这个工作正常。如果您对此有任何疑问,请告诉我。
