Troubleshooting the lack of response in ASP.Net MVC when utilizing OfficeOpenXml for a new Excel file creation

Situation

I have encountered an issue while generating an Excel file using OfficeOpenXml in C#. The generated file is not being returned to the browser.

Any thoughts on why this might be happening?

Code Snippets

[C#] :

public ActionResult ExportToExcel(string[] emails)
{
    using (var ep = new ExcelPackage())
    {
        var ws = ep.Workbook.Worksheets.Add("Contacts");

        for (var i = 0; i < emails.Length; i++)
        {
            ws.Cells[i + 1, 1].Value = emails[i];
        }

        Byte[] bytes = ep.GetAsByteArray();

        return new FileContentResult(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = "Contacts.xls" };
    }
}

[JavaScript] :

$('#contacts-excel-btn').click(function () {
    var emails = [],
        uniqueEmails = [];

    $('.email-td').each(function () {
        var text = $(this).text();
        if (text) {
            emails.push(text);
        }
    });

    $.each(emails, function (i, email) {
        if ($.inArray(email, uniqueEmails) === -1) {
            uniqueEmails.push(email);
        }
    });

    if (uniqueEmails[0]) {
        $.ajax({
            type: 'POST',
            url: '/Contact/ExportToExcel',
            dataType: 'json',
            traditional: true,
            data: { emails: uniqueEmails }
        });
    }
});

Answer №1

After some thorough research, I successfully resolved the issue at hand.

Following guidance from this insightful article, I made a crucial adjustment to my code:

var bytes = ep.GetAsByteArray();
var fileName = "Contacts.xlsx";

return base.File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);

In light of information provided in this informative source, I decided to switch from an ajax-based approach to utilizing a HTML form method:

[JS] :

$.each(uniqueMails, function (i, el) {
    $('#contacts-excel-form').append('<input type="hidden" name="mails[' + i + ']" value="' + el + '" />');
});

$('#contacts-excel-form').submit();

[C#] :

var mails = Request.Form.AllKeys;

for (var i = 0; i < mails.Length; i++)
{
    ws.Cells[i + 1, 1].Value = Request.Form[mails[i]];
}

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

Identifying a postback in the frontend of an aspx application: A beginner's guide

Is there a way to detect a postback in the frontend in order to use JQuery to update a class upon page load? I would like to know how to accomplish this. ...

AngularJS Issue: The function 'FirstCtrl' is missing and is undefined

Currently, I am enrolled in the AngularJS course on egghead.io and have encountered an issue that seems to be a common problem for others as well. Despite trying various solutions found here, none seem to work for me. In the second lesson video, the instru ...

What are some tips for keeping the bootstrap datepicker constantly visible?

Description I have successfully implemented the use of an 'input type=date' as a datepicker within bootstrap 5.3, allowing users to select dates for data viewing. However, the issue I am facing is that the datepicker is only visible upon clicki ...

Updating div with specific class based on selected values

I have utilized Angular to display content based on selected values from a dropdown menu. Now, I am seeking a solution to dynamically add a CSS class to a div when specific values are chosen. In other words, I want to apply certain styling to the div base ...

The process of triggering an action after three mouse clicks

I'm fairly new to coding and I'm currently trying to solve a problem where a div should disappear after being clicked three times. I've managed to achieve this for one or two clicks, but getting it to work for three clicks is proving to be a ...

Vue.js custom confirmation component failing to open within v-menu

I am having trouble displaying a confirmation component every time a button in the header is clicked. Currently, it only opens when clicking elements outside of the dropdown using v-menu. App.vue <template> {{isConfirmDialogVisible}} <div cla ...

What is the process for retrieving a list of files from TFS that were modified on a specific date within a designated workspace?

I need to compile a record of files that have been updated (either checked out or checked in) on a specific date. My function takes user names and their corresponding workspace names as inputs. Any ideas for how to approach this task? ...

Utilizing Knockout to Load JSON Data in DevExtreme

As a newcomer to both javascript and devextreme, I am currently navigating my way through. I successfully created a webpage that loads a json file, but I'm facing challenges implementing it using devextreme. I have a dxDataGrid where I intend to disp ...

Steps for creating a file selection feature in Chonky.js

I recently integrated the Chonky library into my application to build a file explorer feature. One challenge I am facing is figuring out how to select a file and retrieve its unique ID when the user double clicks on it. const [files, setFiles] ...

Creating a React.js component and setting an initial value within it

Recently delved into the world of React.js and currently attempting to create a reusable header that can switch between two states: one for when the user is logged in, and another for when the user is not logged in. // Header.js var Header = React.createC ...

Searching for the right approach to implementing useState with count in order to efficiently add new items in Next.js

Although my code currently functions, I have a feeling that I am not utilizing the useState and useEffect hooks in the best way to achieve my ultimate goal. Let me explain further - I have a button with an onClick event in a separate component, which passe ...

Guide on how to retrieve information from an API and populate it into a dropdown menu

Currently, I am developing an MVC application that interacts with an API. My goal is to call a specific method from the API in order to populate data into a combo-box. However, as a newcomer to this technology, I am unsure of the best approach to take. An ...

Struggling to Parse JSON Arrays in Node.js

Embarking on a journey with Node JS and Express, I find myself facing the challenge of developing a small proof of concept API in Node. The main hurdle I'm currently encountering stems from my limited understanding of how to parse JSON arrays to extr ...

Highlighting n-grams in a contenteditable div

My query does not pertain to extracting n-grams, but rather focuses on highlighting 1/2/3/4 grams within a content editable div. I have a div with some text in it. The n-grams are retrieved from the backend and should be highlighted within the div. I am a ...

The dropdown feature in Bootstrap 5 seems to be malfunctioning in Angular 12

I am facing issues while trying to implement the Bootstrap 5 dropdown in Angular 12. After installing all required packages and adding them to the angular.json file, I still cannot get it to work properly. Even after copying the example directly from the ...

Using canvas to smoothly transition an object from one point to another along a curved path

As a beginner in working with canvas, I am facing a challenge of moving an object from one fixed coordinate to another using an arc. While referring to the code example of a solar system on https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutori ...

What methods does webpack use to minify CSS links within HTML code?

As a newcomer to webpack, I am looking to compress and reference linked CSS files in HTML. Below is the code snippet I am working with: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" ...

Is it acceptable to use the return value of false in order to resolve the ESLint consistent-return error when working with asynchronous functions

When working with ExpressJS, I encountered a situation where I needed to execute and adhere to ESLint rules in my code. One particular rule that caused an issue is "consistent-return", which flagged the following code snippet: function getUsers( req, res, ...

Attempting to retrieve the mesh object using A-Frame's getObject3D('mesh') function results in an undefined value after several attempts

In an attempt to obtain a bounding box for an obj-model in A-frame, I came across two helpful links on stackoverflow that I will reference here: How to get bounding box information from a 3D object in A-frame? Any way to get a bounding box from a three.js ...

Setting the default selection in a closed dropdown menu with ng-Options

In my Angular project, I have a select dropdown that is populated from an array. Each entry in the array is in lowercase format. The variable "selected" that I use in other parts of my code needs to be in lowercase. However, the entries displayed in the ...