[英]C# create xls or csv file and create link to download the file
我現在有這種情況:
我在SQL Server中有一個表,還有一些網頁用戶定義的查詢,這些查詢生成顯示結果的結果頁。 控制器功能均已准備就緒。
現在,我希望能夠將結果下載到訪問該網站的本地計算機上。 我不確定結果如何。 我已經搜索了它,xls和csv文件似乎都非常簡單明了。 但是他們只創建一個文件,然后將其保存到服務器端。
所以我的問題是:
是否必須通過創建臨時文件==>將臨時文件下載到客戶端==>刪除服務器上的臨時文件來完成任務?
如果必須這樣做,如何創建用於下載該臨時文件的按鈕? 如果同時服務多個用戶,將會發生什么?
不知道現在該怎么辦,任何幫助將不勝感激。
您應該根據從Sql Server收到的數據創建MemoryStream。 使用下面的代碼創建一個新類。
public abstract class FileActionResult : IHttpActionResult
{
private string MediaType { get; }
private string FileName { get; }
private Stream Data { get; }
protected FileActionResult(Stream data, string fileName, string mediaType)
{
Data = data;
FileName = fileName;
MediaType = mediaType;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
Data.Position = 0;
var response = new HttpResponseMessage
{
Content = new StreamContent(Data)
};
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentType = new MediaTypeHeaderValue(MediaType);
response.Content.Headers.ContentDisposition.FileName = FileName;
response.Content.Headers.ContentLength = Data.Length;
return Task.FromResult(response);
}
}
public class ExcelFileActionResult : FileActionResult
{
public ExcelFileActionResult(Stream data) : base(data, "Exported.xls", "application/vnd.ms-excel")
{
}
}
從Controller調用代碼。
return new ExcelFileActionResult(stream);
流是內存流。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.