5

I am trying to download a excel file through Web API (using Entity framework). The download is working but I am getting some error dialog about file corrupt when trying to open the file.

Web API code as below:

  public HttpResponseMessage GetValue(int ID, string name)
    {

    MemoryStream stream;
    try {
        using (DataContext db = new DataContext()) {
            dynamic fileObj = (from c in db.FileList c.ID == IDc).ToList();
            stream = new MemoryStream(fileObj(0).File);
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue(fileObj(0).FileContentType);
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = name };
            return result;
        }
    } catch (Exception ex) {
        return Request.CreateResponse(HttpStatusCode.InternalServerError);
    }
}

It opens the file with two error dialog and following message.

Excel completed file level validation and repair. Some parts of this workbook may have been repaired or discarded

enter image description here

enter image description here

6
  • Post upload file code. And a side note: returning InternalServerError on exception in unnecessary, it is web api default behavior. Commented Jun 19, 2015 at 15:24
  • Did you ever resolve this? Commented Jan 28, 2016 at 6:27
  • Yes. I did resolve it. There was error in the code which was uploading the file to SQL Server. Download was correct. So fixed the upload and it was fine. Do you have similar problem? I can post the code if I can find. Commented Feb 1, 2016 at 15:12
  • 4
    I've the same problem. I'm generating the excel file using EPPlus. If I generate it in a console application and save it in file system the excel is working fine. If I send the same stream as HttpResponseMessage in web API I'm getting the same repair alert. Once you click yes, the excel opens fine. But I want to remove that alert. Commented Aug 31, 2016 at 18:33
  • Maybe error is with the upload! Can you paste the code for upload (web api)? I don't have old code now as it was done for one client Commented Sep 2, 2016 at 12:44

2 Answers 2

1

Trying to solve the same. I compared 2 epplus versions: 4.5.3.3 against 5.2.1. The latter one included a code for closing the stream in the GetAsByteArray procedure. So, I just added those lines to the 4.5.3.3 version and it worked like a charm. Looks like the stream initially included some garbage bites which must be deleted before pumping the file data into that stream. Tested with the NetCore 3.1 web application. Hope it will solve the issue in your case.

if (save)
{
    Workbook.Save();
    _package.Close();

    /* start of added code */
    if (_stream is MemoryStream && _stream.Length > 0)
    {
        CloseStream();
    }
    /* end of added code */

    _package.Save(_stream);
}

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

Comments

0

I had the same issue, problem is not in the web api code, but it is in the client side code. For me i was using jquery. Following code fixed it for me.

I was creating a blob from the result, which is not required as, result is already a blob.

 window.URL.createObjectURL(result);

Note that i am creating object straight away from the result. Full Jquery code below.

Credit goes to mgracs in here

$.ajax({
                type: 'POST',
                url: url + "/download",
                data: data,
                xhr: function () {
                    var xhr = new XMLHttpRequest();
                    xhr.responseType = 'blob'
                    return xhr;
                },
                success: function (result, status, xhr) {
                    var filename = "";
                    var disposition = xhr.getResponseHeader('Content-Disposition');
                    if (disposition && disposition.indexOf('attachment') !== -1) {
                        var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                        var matches = filenameRegex.exec(disposition);
                        if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                    }

                    var link = document.createElement('a');
                    link.href = window.URL.createObjectURL(result);
                    link.download = filename;
                    link.click();

                }, error: function (a, b) {
                    console.log('Error');
                }
            });

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.