简体   繁体   中英

C# create xls or csv file and create link to download the file

I now have this scenario:

I have a table in SQL Server, and a handful of webpage-user-defined queries that generates a results page showing the results. The controller functions are all ready to use.

Now I would like to be able to download the results to local computers accessing the website. I'm not sure yet what to put the results into. I've searched for it and both xls and csv files seem pretty straight-forward enough. But they only create a file and then save it onto the server side.

So my questions are:

  1. Does the task must be accomplished by creating a temporary file ==> download the temporary file to client ==> delete the temporary file on the server?

  2. If it must be so, how do I create a button for downloading that temporary file? And what will happen if it is serving multiple users at the same time?

Not sure what to do now and any help would be appreciated.

You should create a MemoryStream from the data received from Sql Server. Create a new class with the code below.

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")
        {
        }
    }

Calling code from Controller.

   return new ExcelFileActionResult(stream);

stream is the memorystream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM