Download data in CSV, Excel, PDF file types using AngularJS

I need to incorporate functionality in my app that allows users to export table data in CSV, Excel, and PDF formats.

My app is being developed using angularjs 1.2.16.

Exporting data to Excel

To export the table to XLS format, I have included the following script:

<script src="https://rawgithub.com/eligrey/FileSaver.js/master/FileSaver.js" type="text/javascript"></script>

To export the table to XLS format, I have used the following code :

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

The above code works perfectly fine.

Exporting data in CSV and PDF

Similarly, I would like to be able to export data in CSV and PDF formats as well.
I tried using for exporting data in CSV but encountered issues when opening the file in ubuntu libre office (corrupted data).
Can someone guide me on how to export table data in CSV, Excel, and PDF formats in angularjs?

Answer №1

If you want to transfer data from AngularJS to XLS, XLSX, CSV, and TAB file formats, you can utilize the Alasql JavaScript library along with the XLSX.js library found at Alasql.

Make sure to include these two essential libraries in your code:

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

To export data into an Excel format, create a function within the controller code:

function myCtrl($scope) {
    $scope.exportData = function () {
       alasql('SELECT * INTO XLSX("mydata.xlsx",{headers:true}) FROM ?',[$scope.items]);
    };
    $scope.items = [{a:1,b:10},{a:2,b:20},{a:3,b:30}];
};

Afterward, include a button (or any other link) in your HTML:

<div ng-controller="myCtrl">
    <button ng-click="exportData()">Export</button>
</div>

Feel free to test out this example on jsFiddle.

If you need to save data in CSV format, employ the CSV() function:

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

You can also use functions like TXT(), CSV(), TAB(), XLS(), or XLSX() for specific file formats.

Answer №2

If you're looking for a simple way to export data in CSV format without manipulating the DOM, then ngCsv is the perfect solution for you. By directly exporting an array, you can easily create CSV files with ease. Take a look at the example below to see ngCsv in action.

Here is the HTML:

 <h2>Export {{data}}</h2>
  <div>
      <button type="button" ng-csv="dataArray" filename="example.csv">Export</button>
</div>

And here is the JavaScript:

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

function Controller($scope) {
    $scope.data = "Data";
    $scope.dataArray = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}];                            
}

Answer №3

Is there a way to modify the file extension of the registered document, such as changing "f:\folder\report.html" to a directory?

var data = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8" }); 
saveAs(data, "report.xls");

Answer №4

After exploring multiple methods, I have arrived at the following solution, which is typesafe (DefinitelyTyped):

   exportAsExcel(tableId: string, fileName: string, linkElement: any) {



        var uri = 'data:application/vnd.ms-excel;base64,',
            template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
            base64 = function (s) {
                return window.btoa(decodeURI(encodeURIComponent(s)));
            },

            format = function (s, c) {
                return s.replace(/{(\w+)}/g, function (m, p) {
                    return c[p];
                });
            };
        // retrieve table data
        var table = document.getElementById(tableId);
        var ctx = {
            worksheet: fileName,
            table: table.innerHTML
        };
        // if using IE, save file as blob (tested on IE10 and IE11)
        var browser = window.navigator.appVersion;
        if ((browser.indexOf('Trident') !== -1 && browser.indexOf('rv:11') !== -1) ||
            (browser.indexOf('MSIE 10') !== -1)) {
            var builder = new MSBlobBuilder(); 
            builder.append(uri + format(template, ctx));
            var blob = builder.getBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 
            window.navigator.msSaveBlob(blob, fileName + '.xlsx'); 
        } else {
            var element = document.getElementById(linkElement);
            var a = document.createElement('a');
            a.href = uri + base64(format(template, ctx));
            a.target = '_blank';
            a.setAttribute('download', fileName + '.xlsx');
            document.body.appendChild(a);
            a.click();

        }
        toastr.success("Great job!", "An Excel report has been generated for you and will be downloaded in your browser.");
    }

A big thank you to all those who contributed to the various articles.

Answer №5

Exporting data from tables in various formats like Json, Xml, and Pdf is essential for effective data management.

If you want a detailed guide on how to export table data using Angularjs and Jquery.js, take a look at this helpful resource: . Keep in mind that this method may not be compatible with Internet Explorer.

To successfully implement this feature, ensure you have the following prerequisites: - Angularjs - Jquery.js - Necessary files: tableExport.js, JqueryBase64.js, html2canvas.js, base64.js, Jspdf.js, sprintf.js

<script type="text/javascript">
    var myAppModule = angular.module('myApp', []);
    myAppModule.controller('myCtrl', function ($scope) {
        $scope.exportData = function () {
            $('#customers').tableExport({ type: 'json', escape: 'false' });
        };
        $scope.items = [
            {
                "FirstName": "Prathap",
                "LastName": "Kudupu",
                "Address": "Near Anjana Beach"
            },
            {
                "FirstName": "Deepak",
                "LastName": "Dsouza",
                "Address": "Near Nariman Point"
            }
        ];
    });
</code></pre>

<p></p>
</div></answer5>
<exanswer5><div class="answer" i="43475709" l="3.0" c="1492516808" a="UHJhdGhhcCBLdWR1cHU=" ai="2480971">
<p>We can easily export table data into different formats such as Json, Xml, and Pdf.</p>

<p>You can refer to a comprehensive explanation at <a href="http://www.prathapkudupublog.com/2015/10/angular-export-to-table.html" rel="nofollow noreferrer">http://www.prathapkudupublog.com/2015/10/angular-export-to-table.html</a>. Please keep in mind that this technique might not function properly in Internet Explorer.</p>

<p>For successful implementation, make sure you have the following components:
- Angularjs
- Jquery.js
- Required libraries: tableExport.js, JqueryBase64.js, html2canvas.js, base64.js, Jspdf.js, sprintf.js</p>

<pre><code><script type="text/javascript">
    var myAppModule = angular.module('myApp', []);
    myAppModule.controller('myCtrl', function ($scope) {
        $scope.exportData = function () {
            $('#customers').tableExport({ type: 'json', escape: 'false' });
        };
        $scope.items = [
            {
                "FirstName": "Prathap",
                "LastName": "Kudupu",
                "Address": "Near Anjana Beach"
            },
            {
                "FirstName": "Deepak",
                "LastName": "Dsouza",
                "Address": "Near Nariman Point"
            }
        ];

    });

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

extract specific data from JSON using JavaScript

Dealing with JSON data can be tricky, especially when working with multiple sets of information to choose from. When I inspect the data in my JavaScript code using console.log(contacts.data["all"]);, I can see the returned objects clearly. Here's a ...

The issue of transform scale not functioning properly in conjunction with background clip and gradients in CSS

Looking to transform a div with the transform: scale(-1,1) property while using background-clip: text on the text within it. However, this causes the text to disappear. Here's what I've attempted: .reverse { transform: scale(-1, 1); } .gr ...

Send a JavaScript variable to Twig

I am trying to pass a JavaScript variable to a twig path but the current method I am using is not working as expected. <p id="result"></p> <script> var text = ""; var i; for (varJS = 0; varJS < 5; varJS++) { text += "<a href= ...

Javascript updating text according to input in textbox functions properly initially, but the changes disappear afterward

This solution functions correctly for a brief moment before disappearing. function checkTFW() { var TFW = document.getElementById("TFW").value if (TFW == "mexicans") { document.getElementById("image").innerHTML = "<h1>Success!</h1>"; ...

Using Promises with setTimeout

I have encountered a challenge with the following question: Create a function that takes a number as a parameter and after x milliseconds (within an interval of 1 to 100 ms using setTimeout along with Math library's floor and random functions), either ...

Extract data from Markit On Demand API using JavaScript and AJAX

I'm struggling to properly parse the response from the API. While I can retrieve the entire response, I am a bit lost on how to effectively parse it. Below is my code snippet: <!DOCTYPE> <html> <head> <style> img ...

Musical backdrop for an online game platform

Currently, I am working on developing a game using HTML. I am trying to figure out the best way to incorporate music into the gameplay. Any suggestions on how I can add music to my web-based game? ...

Utilizing JavaScript and jQuery libraries in conjunction with periods

I am a bit puzzled about when to include the period before referencing class names. For instance, in this code snippet, why is a period included before the first use of the 'active-slide' class but not for the other two instances? var primary = ...

Having issues with dynamic components in Nuxt using Bootstrap 5

I've been working on integrating Bootstrap 5 into my Nuxt project. While the styles are coming through perfectly, anything that previously relied on jQuery is not functioning as expected. The steps I followed for installation: Downloaded files fr ...

Employing parseFloat() and parseInt() functions together with regular expressions in JavaScript for converting a Comma Separated Values (CSV

I've been working on converting a CSV file to a local 2D array and I'm curious if there's a more efficient method of changing strings to floats/int rather than relying on regex paired with parseFloat() / parseInt. Any bright ideas or sugges ...

Mistakes in AngularJS pagination

I attempted to incorporate an Angular UI pagination directive found here -> http://angular-ui.github.io/bootstrap/#/pagination The issue arises when I click on any of the pagination buttons, resulting in the following error message. Error: [$compile:n ...

Whenever I refresh the page, the useEffect hook in React.js returns an empty array for the URL

When the filterOnClick function is called, it returns the necessary "fdata". Console : [[Prototype]]: Array(2) 0: {filter: 'countries', values: Array(3), search: '', checkedValue: 'india'} 1: {filter: 'states', va ...

Modify a single field in user information using MySQL and NodeJS

I am currently working on developing a traditional CRUD (create, read, update, delete) API using NodeJS/Express and MySQL. One of the routes I have created is responsible for updating user information, which is functioning correctly. The issue: When I d ...

I'm facing a minor hurdle while trying to add bcrypt to my package.json

My project is underway and I've begun installing packages, but I ran into an error specifically while trying to install bcrypt. First attempt at installing bcrypt. npm install bcrypt Error encountered: > [email protected] install C: ...

Gulp is failing to convert SCSS files into CSS

I'm having trouble getting gulp to compile my SASS code into CSS automatically. What could be the issue? file structure: public -css --styles.css -index.html sass -styles.scss gulpfile.js package.json Gulpfile: var gulp = require('gulp') ...

`How to resolve page timeout issue caused by looping when using Response.Redirect?`

Currently, I am in the process of building a page that involves creating a large number of files within a folder. Once the task is completed, I compress the folder into a zip file and provide the client with a download link. To keep track of these files, I ...

Alternative for Jquery: a new Hash Table solution using Prototype JS

Greetings everyone! I have experience as a prototype JS developer but now I am transitioning to jQuery for work/client reasons. One feature I really liked in Prototype was the Hash class, such as var h = new Hash();. However, I understand that jQuery doe ...

Utilizing the initial entry in MongoDB exclusively

I have developed a unique adventure command that searches for a player's profile in a Mongo database to calculate various game metrics such as xp and coins. While my other database commands are working flawlessly, this particular command is causing an ...

The command 'npm install -g bigcommerce-stencil/stencil-cli' failed to run properly in the Windows command prompt

Having successfully completed all installations on my Windows 7 SP1 PC, I attempted to run the following command: npm install -g bigcommerce-stencil/stencil-cli Unfortunately, I encountered an error as shown in the screenshot below: error screen For mo ...

Transferring information from a JavaScript function to an action method in an ASP.NET MVC controller

Despite searching through numerous posts on SO in an attempt to solve my problem, I have not made much progress. My goal is to pass data from a JavaScript function (DropdownChange()) to an MVC controller's action method as a parameter based on the sel ...