0

I use Aspose.Cells to create excel file.

Actually I'm trying to save xls file on the disk and I can't resolve this problem. This is my get method.

[Route("xls")]
    [HttpGet]
    public HttpResponseMessage Export()
    {
        try
        {
            string dataDir = KnownFolders.GetPath(KnownFolder.Downloads);
            //var workbook = TransferService.Export();  //TODO get xml
            Workbook workbook = new Workbook();              
            var stream = workbook.SaveToStream();   

            // I need save this workbook

            return Request.CreateResponse(HttpStatusCode.OK); //it's not important here
        }
        catch (Exception ex)
        {

            return Request.CreateResponse(HttpStatusCode.InternalServerError); //it's not important here
        }
    }

Also I have function which is called onClick

function exportToXls() {
    $.get(exportURI, function (response) {
        return response;
    });
}

When someone clicks it should save the file on his disk(or open browser where I could choose the place and name). How to solve this?

4
  • You mean to save the file to the web server's disk or the user's disk? The second one is not something you can control. Commented May 3, 2016 at 13:42
  • Yes , I'd like to save this file on client disk. Can't I transfer file to client and save this? Commented May 3, 2016 at 13:44
  • You cannot set the path where the file will be saved. You can send the file to the browser but you have no control where the file will be eventually saved, this is handled by the browser. Commented May 3, 2016 at 15:07
  • What Reference should I need to add for new Workbook();? Commented Jul 28, 2016 at 7:08

3 Answers 3

2

C#

    [Route("xls")]
    [HttpPost] // can use Get, but Post seems to be recommended
    public HttpResponseMessage Export()
    {
        var response = new HttpResponseMessage();

        try
        {
            // Create workbook
            var wb = new Workbook();

            /* ** fill in workbook / worksheet content ** */

            // save workbook to MemoryStream
            var stream = new MemoryStream();
            wb.Save(stream, SaveFormat.Xlsx);
            stream.Position = 0;    // important!

            // add stream to response
            response.Content = new StreamContent(stream);

            // set Headers
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(dispositionType: "attachment"); // or "inline"
            response.Content.Headers.ContentDisposition.FileName = wb.FileName; // or other means of getting filename
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(mediaType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.Content.Headers.ContentLength = stream.Length;

            // set the success code
            response.StatusCode = HttpStatusCode.OK;
        }
        catch(Exception ex)
        {
            response.StatusCode = HttpStatusCode.InternalServerError;
            response.Content = null; // just in case
            response.ReasonPhrase = ex.Message;
        }

        return response;
    }

If you have CORS enabled, you may need to allow the Content-Disposition header:

    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute(origins: "*", headers: "*", methods: "*");
        cors.ExposedHeaders.Add(item: "Content-Disposition");
        config.EnableCors(cors);

        /* The rest of WebAPI configuration */
    }

For the Javascript side -- the answer here may help. (Note: make sure you set the method to POST, or change my example to GET.)

Sign up to request clarification or add additional context in comments.

1 Comment

Just what I am looking for my CORS problem when trying to export to excel
1

In ASP.NET, you can send your XLS or XLSX file to browser via the following code.

C#

//Save file and send to client browser using selected format
if (yourFileFormat == "XLS")
{
      workbook.Save(HttpContext.Current.Response, "output.xls", ContentDisposition.Attachment, new XlsSaveOptions(SaveFormat.Excel97To2003));

}
else
{
      workbook.Save(HttpContext.Current.Response, "output.xlsx", ContentDisposition.Attachment, new OoxmlSaveOptions(SaveFormat.Xlsx));
}

HttpContext.Current.Response.End();

The above code will send XLS file to browser. If you change this line

if (yourFileFormat == "XLS")

to something like

if (yourFileFormat == "XLSX")

then it will send XLSX file to browser. Please download the ASP.NET Web Application Project from the following link to see the above code running.

Project Link:

http://www.aspose.com/community/forums/293730/postattachment.aspx

Please do not use Workbook.SaveToStream() method to get memory stream object. Please check the following code, how you can get memory stream object of different formats like XLS, XLSX etc.

//Create workbook object
Workbook wb = new Workbook("source.xlsx");

//This is how to save Workbook to XLS format
MemoryStream ms1 = new MemoryStream();
wb.Save(ms1, SaveFormat.Excel97To2003);

//Just to check if memory stream is good and contains XLS bytes
byte[] b1 = ms1.ToArray();
File.WriteAllBytes("output.xls", b1);

//This is how to save Workbook to XLSX format
MemoryStream ms2 = new MemoryStream();
wb.Save(ms2, SaveFormat.Xlsx);

//Just to check if memory stream is good and contains XLSX bytes
byte[] b2 = ms2.ToArray();
File.WriteAllBytes("output.xlsx", b2);

Note: I am working as Developer Evangelist at Aspose

1 Comment

Downvoted because doesn't answer the question. Answer is for MVC, not WebAPI.
0

Using .net so slightly adjusted from Andews version using the File action result.

[HttpGet("download")]
    public async Task<IActionResult> DownloadSystem()
    {
        var workbook = new Workbook();
        var fileName = $"Report.xlsx";
        var cd = new System.Net.Mime.ContentDisposition
        {
            FileName = fileName,
            Inline = false, 
        };
        Response.Headers.Add("Content-Disposition", cd.ToString());
        var stream = new MemoryStream();
        workbook.Save(stream, SaveFormat.Xlsx);
        stream.Position = 0;
        return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.