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

Testing API calls with ReactJS

I'm diving into Reactjs development and have encountered a challenge. I created an App that makes API calls to https://jsonplaceholder.typicode.com/users. However, when testing the API call, I ran into issues. In addition, I built a simple WebApi pro ...

Material design for Angular applications - Angular Material is

Recently, I decided to explore the world of Angular and its accompanying libraries - angular-material, angular-aria, and angular-animate. I'm eager to experiment with this new styling technique, but it seems like I've hit a roadblock right at the ...

Error code 405 (METHOD NOT ALLOWED) is received when attempting to make a post request to an API

Struggling to develop a basic front end that can communicate with my API. The API functions properly as I am able to retrieve and send data using the POSTMAN client. Fetching data from the server and displaying it on the frontend works fine, but encounteri ...

Is it possible to upload a file using Angular and ASP.NET Web API Core?

I am encountering an issue with CORS policy while making requests. It works fine when the content-type is set to 'application/json'. However, when I try to upload a file using content-type 'multipart/form-data', I receive an error: XML ...

Messages using JQuery input technology

My form includes two inputs. The first input must be completed before moving on to the second. If the user selects the second input before the first, they will receive a message instructing them to fill out the initial input. I now want to ensure that aft ...

Angular q.all: comparing immediate and delayed responses

Seeking advice on methodology: I currently utilize $q.all to handle multiple promises in a single return, processing all results as one request. For instance: $q.all([promise1(),promise2(),promise3(),promise(4),promise5()])..then(function(response){ ...} ...

Using JavaScript to redirect browser with a specific string

My goal is to redirect all users who visit a specific URL to another page. While this redirection works effectively, I now need to implement it with a tracking URL. The issue arises when Javascript automatically adds a "/" in front of the tracking string ...

Receive the deleted entry upon clicking the thead | Error发

Is there a way to permanently delete a row in a datatable? If I delete all the rows, I would like the datatable to display the default message of "No data available". I have attempted some POST requests : But with no success. DataTables remove row butto ...

Tips for Parsing an Atom XAML Document in Windows Presentation Foundation

I am working on a WPF Application and I need to write code that can read Atom XAML feed. The feed contains web links like www.myweblink/NewXaml.xaml. My goal is for the code to use these links to extract the title and description from the XAML file specifi ...

Node.js error: Headers cannot be set once they have been sent

I'm struggling with sending form data through express.js and encountering the following error: After establishing communication, it's not possible to modify headers. This is the current state of my code: app.post('/api/users/profile/:us ...

Unique title: "Curved Blocks with Unusual Shapes in SVG Path

Hey there, I'm new to working with SVG and Highcharts. I found a jsfiddle online that I would like to customize for my project, but I've encountered an issue with the rounded corner blocks of lines in the Result panel. Here is the link to the js ...

What is the best way to ensure that my transitionend event is triggered?

I'm currently exploring the <progress> element and attempting to incorporate a CSS transition to achieve a smooth progress bar effect as its value increases. Despite my efforts, I can't seem to trigger JS after the transitionend event occur ...

Creating a dynamic onclick function that depends on a variable passed from a while loop in PHP

If you're familiar with PHP, I have a scenario for you. Let's say there's a list of items generated using a while loop in PHP. Each item has a sub-list that should only appear when clicked on. I tried using the onclick function in jQuery but ...

The CKEditor value is set to the result of the dropdown selection

I need to implement a dropdown feature on my form where the options correspond to titles of content in my database. Once an option is selected, I want the corresponding content to display in a CKEditor field. I'm attempting to achieve something simil ...

When utilizing ASP.NET, the return value from a stored procedure will only retrieve the initial character

When running a stored procedure, I am only getting the first character as a return value. Exec sp_Auto_Gen_TTBDBatNo 'TT', '' in SQL Server returns the entire string, but when used in ASP.NET, it only retrieves the first character. Ho ...

Could use some assistance in developing a custom jQuery code

Assistance Needed with jQuery Script Creation <div>Base List</div> <div id="baseSection"> <ul class="selectable"> <li id="a">1</li> <li id="b">2</li> <li id="c">3</li> ...

Efficiently select multiple classes in Material UI with just one target

I'm currently working with Material UI and I want to update the color of my icon class when the active class is triggered by react-router-dom's NavLink Here is my code: import React from "react"; import { makeStyles } from "@mater ...

Comparing Data Manipulation Techniques: Server Side vs Client Side Approaches in Reddit API Integration

As I delve into creating a simple Node/Express web application that fetches data from the Reddit API, performs some alterations on it, and intends to present this information using Charts.js on the client side, I find myself facing a dilemma due to my limi ...

Retrieve the file's source and name using AngularJS

Is it possible to retrieve the name, path, and size of a selected file in an input field using AngularJS before uploading it? <input type="file" ng-model="fileContent" on-read-file="showContent($fileContent)" /> $scope.showContent = function($fileC ...

Tips for rearranging objects within a jsPDF document to prevent vertical overlap when a table grows in size

I am new to React and Javascript. I have been struggling to find a solution to my issue while trying to create a .pdf document for a customer invoice using "jsPdf" along with its plugin "jspdf-autoTable". So far, everything is being generated correctly by ...