Exporting a Javascript Object to an XLS file in Angular JS: A Step-By-Step

Currently, I have an object stored in my controller that I need to export as either a .xls or .csv file. I have tried various methods, including the following:

HTML

<script src="https://rawgithub.com/eligrey/FileSaver.js/master/FileSaver.js" type="text/javascript" />
<div ng-controller="myCtrl">
    <button ng-click="exportData()">Export</button>
    <br />
    <div id="exportable">
    <table width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>DoB</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="item in items">
                <td>{{item.name}}</td>
                <td>{{item.email}}</td>
                <td>{{item.dob | date:'MM/dd/yy'}}</td>
            </tr>
        </tbody>
    </table>
    </div>
</div>

Javascript

function myCtrl($scope) {
    $scope.exportData = function () {
        var blob = new Blob([document.getElementById('exportable').innerHTML], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
        });
        saveAs(blob, "Report.xls");
    };

    $scope.items = [{
        name: "John Smith",
        email: "[email protected]",
        dob: "1985-10-10"
    }, {
        name: "Jane Smith",
        email: "[email protected]",
        dob: "1988-12-22"
    }, {
        name: "Jan Smith",
        email: "[email protected]",
        dob: "2010-01-02"
    }, {
        name: "Jake Smith",
        email: "[email protected]",
        dob: "2009-03-21"
    }, {
        name: "Josh Smith",
        email: "[email protected]",
        dob: "2011-12-12"
    }, {
        name: "Jessie Smith",
        email: "[email protected]",
        dob: "2004-10-12"
    }]
}

However, this method does not work with paginated tables. Is there a direct way to export objects (like $scope.item in this example) to a file (xls, csv)?

Answer №1

Indeed, it is possible to store your data using the Alasql JavaScript library in conjunction with the XLSX.js library. Below is a sample of how to achieve this:

To begin with, you need to incorporate two JavaScript libraries into your webpage:

  • alasql.min.js
  • xlsx.core.min.js

Next, update the exportData() function in your code with the following:

  $scope.exportData = function () {
      alasql('SELECT * INTO XLSX("john.xlsx",{headers:true}) FROM ?',[$scope.items]);
  };

For CSV files, simply utilize the CSV() function:

  alasql('SELECT * INTO CSV("john.csv",{headers:true, separator:";"}) FROM ?',[$scope.items]);

Feel free to experiment with this demonstration on jsFiddle.

Answer №2

If you're looking to easily export data in CSV format without manipulating the DOM, then the ngCsv module is a perfect solution. It allows you to export an array directly as a CSV file. Check out this example showcasing ngCsv in action.

Here's the HTML:

<h2>Export {{sample}}</h2>
  <div>
      <button type="button" ng-csv="getArray" filename="test.csv">Export</button>
</div>

And here's the Javascript:

angular.module('csv', ['ngCsv']);

function Main($scope) {
    $scope.sample = "Sample";
    $scope.getArray = [{a: 1, b:2}, {a:3, b:4}];                            
}

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

Having trouble accessing env variables from React Component in Next.js?

I recently set up a Next.js project and included an .env file to store environment variables used in my server.js file. However, I am facing an issue when trying to access these variables from a component. Can anyone provide guidance on how to resolve this ...

Experiencing Limitations with Node.JS node-hbase Scan Functionality, Unable to Retrieve More than 1000

I am facing an issue while trying to retrieve records from an HBase table in Node.JS using the node-hbase module, which connects to the rest server. I am able to fetch the first batch of records successfully, but I am struggling to get the next set of re ...

Issues with looping through JSON data retrieved from a request

Today has been a battle with this code, as I tirelessly search for a solution. I've been using the fetch API to retrieve values and I can successfully iterate through the first JSON to grab the ID from the album section. Now, my goal is to use a loop ...

Are HTML entities ineffective in innerHTML in javascript?

Take this example: <script type="text/javascript> function showText() { var text = document.getElementById("text-input").value; document.getElementById("display").innerHTML = text; } </script> <?php $text = "<html>some ...

Transforming dates in JavaScript

So I have a situation where I need to call php from javascript. The URL address is Jun 18 18:00:00 UTC+0200 in the year 2013, but that format is not suitable for my needs. I want to convert it to the format YYYY-MM-DD, either using JavaScript or PHP. An ...

Tips for choosing an option in a form using Selenium with JavaScript

I am currently in the process of automating some tests for a specific form, and I have successfully automated all steps except for selecting an option from a dropdown menu using JavaScript. Here is my code: const {Builder, By, Key} = require("sel ...

What are the signs that indicate a potential code breakage following an upgrade of the JavaScript library in use?

Imagine you have incorporated multiple JavaScript libraries into your website. Your code interacts with various APIs, but occasionally, after an update, one of the APIs changes and causes your code to break without any prior notice. What steps can you tak ...

Fade In/Out Scroll Effect

As the user scrolls down the page, I have a slider that smoothly slides from right to left. What I'm trying to achieve is for the slider to fade out when the last slide is no longer in view during downward scrolling, and fade back in as the last slid ...

The issue is that AngularJS deferred.reject function is not functioning properly, while the $q

I'm struggling to understand the difference between Angular JS deferred and $q. I recently came across this SO Question that delves into the variance between $q.defer() and $q. According to the post: $q.reject serves as a quick way to create a defe ...

When utilizing KineticJS on a canvas that has been rotated with css3, the functionality of the events appears to be malfunctioning

Currently, I'm working on a rotating pie-chart widget using Kineticjs. However, I have run into an issue where the events don't seem to function correctly when drawing on a rotated canvas element (with the parent node being rotated 60deg using CS ...

Discovering the process of obtaining information from a restful API using javascript

I am working on a desktop application using C# (Windows Forms) that includes a web browser component and utilizes JavaScript. My goal is to create a weather forecast for Bulgaria. However, I am unsure about how to retrieve data from the API server. I curr ...

TypeORM is unable to locate the default connection within a class

I have encountered an issue while trying to incorporate TypeORM within a class. It seems to be unable to locate the default connection despite awaiting the connection. I have double-checked the configuration and tested it with .then(), which did work succe ...

I am looking to retrieve the values of checked checkboxes in a MUI multi-select component

I am currently using Material-UI's mui multi select component and I need to determine whether an item is selected or unselected in order to set the correct state value. I have checked the event.target but it does not seem to have a checked attribute. ...

Exploring the equality of objects in NodeJS

Currently, we are in the process of creating tests for a program. Our goal is to develop a functional test that validates whether the output of the program aligns with certain expectations. The data returned from the program consists of a complex JavaScrip ...

Java servlet is unable to interpret the name of an html select tag

Currently, I am implementing a feature where table rows with select boxes are added dynamically and the values of these select boxes are retrieved in a servlet. The process of adding the select boxes is functioning properly; however, when attempting to ret ...

Vue.JS - Dynamically Displaying Property Values Based on Other Property and Concatenating with

I have a reusable component in Vue.js called DonutChart. <donut-chart :chartName="graphPrefix + 'PerformanceDay'" /> The value of the property graphPrefix is currently set to site1. It is used as part of the identifier for the div id ...

Establishing an RSS feed (Google shopping) for an online store built on Vue-storefront

I recently launched a Vue-storefront based online store and now I'm looking to set up Google Shopping ads using an RSS feed for my products. However, I've encountered an error message saying "Unexpected token < in JSON at position 0" when tryi ...

Reorganizing JSON Information

Currently, I am dealing with a JSON file that contains multiple sets of data structured like this: {"name": ["Adelphi University"], "supp": ["Yes: E, WS"], "ed": ["\u00a0"], "online": ["$40"], "ea": ["12/1"], "mid": ["No"], "rd": ["Rolling"], "recs": ...

Preserving and Reversing Drag and Drop Canvas Configurations in HTML5 Canvas

With the help of this innovative JS Fiddle, I have successfully created dynamic canvases and enabled the functionality to drag and drop images across multiple canvases. var next = 4 function addCanvas() { // create a new canvas element ...

Enemy in Three.js advances menacingly towards the player

I'm working with three.js and I've got a spaceship located at coordinates xyz. I want it to fly towards a mesh object representing a planet at coordinates xyz. I've been struggling to figure this out and it's been quite challenging. T ...