Export data table from HTML to Excel successfully implemented with C#

I am currently working on an Umbraco website and developing a custom plugin for the backend that allows users to export an Excel worksheet from an HTML table. In order to achieve this functionality, I am utilizing AngularJS along with a C# controller. Below are the relevant files involved in this process.

//The C# Controller located at /App_Code/ExportBlankDictionaryController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Umbraco.Web.Editors;
using Umbraco.Core.Persistence;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.IO;

namespace AngularUmbracoPackage.App_Code
{
    [Umbraco.Web.Mvc.PluginController("AngularUmbracoPackage")]
    public class ExportBlankDictionaryController : UmbracoAuthorizedJsonController
    {
        //[System.Web.Http.AcceptVerbs("GET", "POST")]
        //[System.Web.Http.HttpGet]
        public void ExportExcell()
        {
            var keys = new System.Data.DataTable("BlankDictionaryItems");
            keys.Columns.Add("Keys", typeof(string));
            keys.Columns.Add("Description", typeof(string));

            keys.Rows.Add("Enter First Dictionary Name Here", " ");

            var grid = new GridView();
            grid.DataSource = keys;
            grid.DataBind();

            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.BufferOutput = true;
            HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=BlankDictionaryItems.xls");
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

            HttpContext.Current.Response.Charset = "";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);

            HttpContext.Current.Response.Output.Write(sw.ToString());
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
    }
}
// The AngularJS controller located at /App_Plugins/datatable/datatable.controller.js:

angular.module("umbraco")
    .controller("AngularUmbracoPackage.ExportBlankDictionaryController", function ($scope, keyResource) {
        keyResource.exportToExcell().then(function (response) {
            alert("Table Generated!");
        })
    });

This is the datatable.resource.js file housed within the same directory:

// Adds the resource to umbraco.resources module:
angular.module('umbraco.resources').factory('keyResource',
    function ($q, $http) {
        // The factory object returned
        return {
            // This calls the API controller we setup earlier
            exportToExcell: function () {
                console.log("button clicked");
                return $http.post("backoffice/AngularUmbracoPackage/ExportBlankDictionary/ExportExcell");
            }
        };
    }
);

If needed, here's the package.manifest.json file:

{
    propertyEditors:[
    {
        name: "DataTable editor",
        alias: "my.datatable.editor",
        editor:{
            view: "~/app_plugins/datatable/table.html",
            valueType: "JSON"
        }
    }
    ],
    javascript: [
    "~/app_plugins/datatable/datatable.controller.js",
    "~/app_plugins/datatable/datatable.resource.js"
    ]
}

Below is the content of the table.html file which serves as the view:

<div class="ExportDiv" ng-controller="AngularUmbracoPackage.ExportBlankDictionaryController">
    <table id="table1" class="table table-bordered" runat="server">
        <thead>
            <tr>
                <th>Key</th>
                <th>Populate Dictionary Item Names in Key Column</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Enter First Dictionary Name Here</td>
                <td></td>
            </tr>
        </tbody>
    </table>
</div>

<button class="btn btn-success" ng-click="exportToExcel()">Export Table</button>

The issue I'm facing is that while the Umbraco page loads successfully and the alert is triggered upon opening the developer section of Backoffice, clicking the Export Table button does not result in any action. My goal is to have the Excel sheet download when this button is clicked. Can you please assist me in troubleshooting this problem? Thank you!

Answer №1

Click the button

angular.module("umbraco")
    .controller("AngularUmbracoPackage.ButtonController", function ($scope, keyResource) {
        $scope.ButtonClickHandler = function(){
             console.log("button clicked!");
             keyResource.exportToExcell().then(function (response) {
                 // handle server response here
            }
        });
    

Next, update the button element to:

<button ng-controller="AngularUmbracoPackage.ButtonController" class="btn btn-primary" ng-click="ButtonClickHandler()">Export Data</button>

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

Do iframes not utilize parental jquery?

I have a homepage that utilizes jQuery by loading it from the ajax google APIs in the head> tag. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js" type="text/javascript"></script> I attempted to use jQuery functions ...

Ways to designate ROLES within the _user database on Cloudant

I am struggling to figure out how to add Roles to users in the Cloudant user database (_users). Despite searching through Google and Cloudant Docs, I have not been able to find a solution. There is mention of a Cloudant _user db, but I can't seem to u ...

What is the process of incorporating HTML into a jQuery program in order to immerse the world in an element?

I am looking to utilize HTML with the value in a checkbox, After adding a shortcode: <label class="HCheck">(this is val 1 )</label> and incorporating jQuery to change it to: <label class="HCheck">(this is val 1 ) ...

Utilize the jQuery autocomplete UI Widget to trigger a select event on a dynamically generated row in a table

Currently, I have successfully implemented a jQuery autocomplete feature on the text input of a table data element called txtRow1. The data for this autocomplete is fetched remotely from a MySQL database and returned in JSON format as 'value' for ...

Newbie: Troubleshooting Vue Errors - "Vue is not recognized"

I'm currently at the beginning stages of learning Vue and am practicing implementing it. However, I keep encountering the errors "vue was used before it was defined" and "Vue is not defined". Below are excerpts from my HTML and JS files for reference. ...

Experiencing an anonymous condition post onChange event in a file input of type file - ReactJS

When using the input type file to upload images to strapi.io, I noticed that an unnamed state is being generated in the React dev tools. Can someone explain how this happened and how to assign a name to that state? state constructor(props) { super(pro ...

CSS Challenge: How to crop an image without using its parent container directly

I'm currently facing a complex CSS challenge that I can't seem to solve. I want to create an image controller (two-by-two layout on two lines) that can display: The top-left image in full size, The top-right with horizontal scrolling, The botto ...

Tips for handling an empty jQuery selection

Below is the code snippet: PHP CODE: if($data2_array[7]['status'] == "OK"){ $degtorad = 0.01745329; $radtodeg = 57.29577951; $dlong = ($lng - $supermercado_lng); $dvalue = (sin($lat * $degtorad) * sin($superm ...

Enable autocomplete feature in a PHP form once the user starts typing their name

After searching for similar questions, I couldn't find any with the same "variables," so here's my dilemma: I have a basic form where I input a name and I want the rest of the form to be filled in automatically (ID). Retrieving data from the da ...

Where do JQuery and framesets vanish to?

Whenever I attempt to use the console to create an element with the tag frameset, it returns no result: $('<div id="content" data-something="hello" />') => [<div id=​"content" data-something=​"hello">​</div>​] $(&apo ...

Retrieving JSON Arrays in PHP through an AJAX Request

Having trouble extracting data from multiple arrays in an AJAX request. Can anyone help? Here's what I'm trying to send: https://i.stack.imgur.com/4MEL4.png Executing a jQuery AJAX POST to a PHP file, but uncertain how to retrieve the data. An ...

Using JavaScript in Node, you can pass an object by throwing a new Error

How can I properly throw an error in my node application and access the properties of the error object? Here is my current code: throw new Error({ status: 400, error: 'Email already exists' }); However, when I do this, I get the following outpu ...

Encountering difficulties while using JavaScript to complete a form due to issues with loading the DOM

Currently, I am attempting to automate the completion of a multi-page form using JavaScript. Below is the script that I am utilizing: // Page 1 document.getElementById("NextButton").click(); // Page 2 completion(document.getElementById("Rec ...

Issue with Express/Node.js route unable to access key values within an object

I am currently struggling with creating a node/express route that fetches data from a MongoDB collection and facing an infuriating issue. The collection in question is named nba_players_v2, and I've tried crafting the following route: router.get(&apo ...

Having trouble with the filtering feature in Material UI Datagrid

I'm currently using Material UI Data Grid to display a table on my website. The grid has an additional filter for each column, but when I click on the filter, it hides behind my Bootstrap Modal. Is there a way to bring it to the front? https://i.stac ...

Sending a `refresh` to a Context

I'm struggling to pass a refetch function from a useQuery() hook into a context in order to call it within the context. I've been facing issues with type mismatches, and sometimes the app crashes with an error saying that refetch() is not a funct ...

Executing the executeScript method in Microsoft Edge using Java and WebDriverWould you like a different version?

I'm currently attempting to execute the following code in Microsoft Edge using WebDriver ExpectedCondition<Boolean> jsLoad = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals(&quo ...

Refresh the HTML content within a specified div element

In my index.html, there is a graph (created using d3.js) along with some code that displays a stepper with a number of steps equal to the child nodes of the clicked node: <div ng-include="ctrl.numlab==2 && 'views/stepper-two-labs.htm ...

Can you assist in resolving this logical problem?

exampleDEMO The code above the link demonstrates how to control input forms based on a button group selection. In this scenario, when a value is inputted on the 'First' Button's side, all input forms with the same name as the button group ...

Creating a cron job that can be rescheduled using Node.js

I am utilizing the node-schedule package from GitHub to create cron jobs. While I have successfully created a basic scheduler, my goal is to make it reschedulable. Within my application, users can initiate tasks for specific dates. This can be easily achi ...