Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel File download through web api. Getting corrupt

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

like image 700
user2739418 Avatar asked Nov 10 '22 11:11

user2739418


1 Answers

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);
}

like image 94
Lukan Avatar answered Dec 09 '22 08:12

Lukan