Corrupted file download after exporting Web API data to Excel

I utilized OfficeOpenXml ExcelPackage to create an excel file from a list of Objects. The download is successful, but upon opening the file, Excel issues a warning that it is corrupted and not saved in the proper file format. I also attempted using FileSaver.js with no success - encountering the same error. Any suggestions on how to resolve this issue?

Server-Side Code:

 ExcelPackage _excelPackage = new ExcelPackage();
 ExcelWorksheet _sheet = _excelPackage.Workbook.Worksheets.Add("New Sheet");
 int currentRow = 1;
            foreach (var prod in Products)
            {
                 _sheet.Cells[currentRow, 0].Value = prod.Id;
                 _sheet.Cells[currentRow, 0].Value = prod.Name;
                 _sheet.Cells[currentRow, 0].Value = prod.Price;
                 currentRow++;
             }

HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);    
byte[] stream = _excelPackage.GetAsByteArray()
response.Content = new ByteArrayContent(stream);

response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "Products.xlsx"
};
return response;

Client-Side (AngularJS Service Code):

var req = {
    url: fpReportsWebAPIURL + 'api/Export/DownloadFile',
    method: 'POST',
    responseType: 'arraybuffer',
    //data: json, //this is your json data string
    headers: {
        'Content-type': 'application/json',
        'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    }
};

return $http(req).then(function (data) {
    var type = data.headers('Content-Type');
    var blob = new Blob([data], {
        type: `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`
    });
    saveAs(blob, 'Products' + '.xlsx');
    return true;
});

Upon opening the Excel, I receive the error message "Excel found unreadable content in Products.xlsx. Do you want to recover the contents of this workbook...".

After inspecting the API response, I noticed that WebApi returns some data in OfficeOpenML format, unsure if this may be causing the issue.

Please assist me in resolving this problem as a similar issue encountered was left unanswered.

Answer №1

It seems like the issue lies in how you are saving the file to a stream. The ExcelPackage object has its own method for saving to a memory stream, which can be resolved by following these steps:

Start by utilizing a using block

using (ExcelPackage xls = new ExcelPackage())

Next, write it to a MemoryStream

MemoryStream ms = new System.IO.MemoryStream();
xls.SaveAs(ms);

Before closing the stream, transfer the contents to your response

response.BinaryWrite(ms.ToArray());
ms.Close(); // Close the MemoryStream 

By implementing these changes, the issue should be resolved.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to change the input source in Ratchet's chat app to come from a text box on the webpage instead of the console

I followed the guidelines on to create a chat app. However, I now want to input data from a text box instead of using conn.send() in the console. How can I achieve this using php? I was successful in redirecting the sent message to an html element like ...

What steps do I need to follow to get this AngularJs Gallery up and running

As I delve into expanding my knowledge in AngularJS, I've encountered some issues while trying to run code on Plunker. Could someone take a look at the code and point out what I might be doing incorrectly? The code snippet is provided below: var a ...

`Issue with multiple replacevariablebyhtml functions not functioning properly within PHPDocX`

When attempting to replace multiple variables in a document using the functions replaceVariableByHTML and replaceVariableByText, I encountered an issue. If I only use replaceVariableByText, everything works fine. However, when I add HTML replacement, the ...

Difficulty encountering issues with JQuery's ajax function

I've encountered different errors in FF, Chrome, and IE, but it seems like there's an issue with the data in $.ajax. Below is the code snippet. Please be gentle with feedback if I have overlooked something obvious. I've spent countless hours ...

Sending parameter(s) to a function in AngularJs

I've been attempting to set up my first AngularJS configuration for a simple task, but so far I haven't had much success despite spending a significant amount of time on it. My Goal: I want users to be able to select an option from a dropdown ...

establish connections within dynamic data table entries

As a newcomer to Javascript, I've been struggling with a particular question for some time now. The challenge at hand involves a dynamic jQuery table where I aim to hyperlink one row of the table data to a .php page in order to perform certain querie ...

Issue with NullReferenceException during deserialization in Newtonsoft JSON.NET

After generating a simple JSON using the WCF Rest client, I encountered an issue when trying to deserialize the response which resulted in a NullReferenceException error in JSON.Net. The JSON structure is as follows: {"Code":-2146232800,"ExceptionType":"I ...

Get the selected value from a dropdown list in Angular after populating the options

I am working with a model within an Angular module. $scope.employee = {} $scope.countries={} $scope..employee.Country_id = 10 $scope.employee.City_id = 50 Next, I am binding two select elements in the following way: $http.get("/api/initdataapi/GetCountr ...

Issue with ForwardRef component in Jest for React Native testing

When attempting to write a test case for my Post Detail screen, I encountered an error that stated: error occurred in the <ForwardRef> component: Here is my test class code: import React from "react"; import { NewPostScreenTemplate } from ...

Images in ListView are refusing to appear. As much as it pains me, I have to inquire: why is this happening?

I am attempting to showcase images in a WinForms ListView that is set in details view mode, but for some reason, the images are not appearing. Despite adding a SmallImageList (and a large one as well), inserting images into them, and populating the ListV ...

Get access to the file upload field using ajax

I'm encountering an issue with accessing the file upload field //HTML <input type='file' name='images' id="images" multiple> ////////////////// $('.bt-add-com').click(function(){ var formdata = new For ...

What is the best way to retrieve the latest files from a Heroku application?

Having recently migrated my Discord Bot to Heroku, I faced a challenge with retrieving an updated file essential for code updates. I attempted using both the Git clone command and the Heroku slugs:download command with no success in obtaining the necessar ...

The component encountered an error because the element type provided was not valid

I've encountered an error that has me stumped: https://i.sstatic.net/glSvr.png I've been trying to locate the HeaderSegment, but it seems to be missing from my project. I've checked for any imports, such as: import HeaderSegment from &apos ...

What is the correct way to utilize the WhatsApp API for sending messages?

Trying to incorporate WhatsApp API notifications into my app has been a challenge. Despite extensive research, I have yet to find an official solution. The existence of the WhatsApp API Business is known, but it currently remains in beta and caters to com ...

Where should Babel and Webpack be placed in your package.json file - under devDependencies or Dependencies?

I'm a beginner when it comes to npm and I have doubts on what should be included in dependencies as opposed to devDependencies. I understand that testing libraries belong in dev, but what about tools like babel and webpack? Should they also be categor ...

Sending Javascript variable to AngularJS

I'm a beginner in the world of AngularJS and JavaScript, and I'm struggling to figure out how to pass a JavaScript variable into my AngularJS controller. Here's the snippet from my html page: <!DOCTYPE html> <html lan ...

How to Set a Background Image for a Div in React?

render(){ const { classes } = this.props; const { imageDescription } = this.props.imgDesc; const { currentIndex } = this.state; var fullPath = `../images/Large/${(imageDescription[currentIndex]).imagePath}.jpg`; con ...

How can we align the top edge of a div to the center of a circle within a separate div in a responsive manner?

I want to create 2 stacked divs: the first div contains a circular image, and the second div contains text. I want the second div to always cover half of the circle, with its upper edge positioned at the center point of the circle. This is my code: .cov ...

A guide on organizing JSX elements based on JSON data

What I Aim to Achieve: I am looking to display a list of elements using the .map method, and then arrange them in descending order based on their date. Despite attempting to use .sort and .filter before rendering the elements, I have not been successful. ...

Obtain JSON data response in PHP with the help of jQuery

Below is the code I am using to make an AJAX call and retrieve data from another PHP file: $.post('<?php echo get_site_url(); ?>/ajax-script/',{pickup:pickup,dropoff:dropoff,km:km}, function(data){ $('#fare'). ...