Export JSON to CSV with AngularJS and ng-csv (Legacy)

In an existing AngularJS 1.x application, the ng-csv directive can turn an array into a downloadable CSV file. Register the ngCsv and ngSanitize modules, supply the report rows, and use csv-header for a separate header row. The example exports six employees with a fixed report filename.

Legacy maintenance example: AngularJS support ended in January 2022, according to its official security policy. The example retains the original AngularJS 1.4.3 and ng-csv 0.3.3 API context for understanding an existing application. These versions are not a supported foundation for a new production project. Modern Angular is a different framework. For a dependency-free browser exporter, see export JSON to CSV with JavaScript.

Short Answer

In the existing AngularJS application, register ngCsv with ngSanitize, pass rows in a fixed column order, and supply the labels through csv-header. This creates a CSV text file; the unsupported AngularJS stack is retained here only for legacy maintenance.

CSV and Excel are different formats

The result is a .csv text file that Excel and other spreadsheet programs can import. It is not an .xlsx workbook and does not contain styles, formulas chosen by the application, or multiple worksheets. Bootstrap can style the on-screen table, but it does not convert or format the CSV file.

Original AngularJS employee table with six records and a Download CSV button
The original employee-report illustration uses Bootstrap styling. The minimal example below keeps the same report and download while omitting that optional styling.

Step 1: Keep the legacy dependencies explicit

Use this only in an isolated maintenance copy of an application that already depends on AngularJS. The standalone example expects these existing assets in a vendor folder, in this order: AngularJS 1.4.3, matching angular-sanitize 1.4.3, then ng-csv 0.3.3. Retain licenses and verify your organization's approved copies. The ng-csv project documents its module and directive API.

jQuery is not required by this example; the old jQuery 3.0 alpha reference has been removed. Bootstrap is optional presentation. A Web Forms application can serve this markup, but the export runs in the browser and does not need a C# or VB.NET handler. You can also save it as a plain HTML page.

Step 2: Create index.html

html
<!DOCTYPE html>
<html lang="en" ng-app="csvApp">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Legacy AngularJS JSON-to-CSV example</title>
</head>
<body ng-controller="MyController">
    <h1>Export employee JSON to CSV</h1>
    <p>Archived AngularJS 1.x maintenance example.</p>
    <button type="button" ng-csv="exportRows"
        filename="Codingvila_NikunjSatasiya_CSV.csv"
        csv-header="['Employee Id', 'Employee Name', 'Department', 'Designation', 'City', 'Contact Number']"
        charset="utf-8">Download CSV</button>
    <table>
        <caption>Sample employee report</caption>
        <thead><tr>
            <th scope="col">Employee Id</th><th scope="col">Employee Name</th>
            <th scope="col">Department</th><th scope="col">Designation</th>
            <th scope="col">City</th><th scope="col">Contact Number</th>
        </tr></thead>
        <tbody><tr ng-repeat="employee in MyCSV track by employee.EmpId">
            <td>{{employee.EmpId}}</td><td>{{employee.EmployeeName}}</td>
            <td>{{employee.Department}}</td><td>{{employee.Designation}}</td>
            <td>{{employee.City}}</td><td>{{employee.ContactNo}}</td>
        </tr></tbody>
    </table>
    <script src="vendor/angular-1.4.3.min.js"></script>
    <script src="vendor/angular-sanitize-1.4.3.min.js"></script>
    <script src="vendor/ng-csv-0.3.3.min.js"></script>
    <script src="employee-export.js"></script>
</body>
</html>

The table has explicit column headings, and each row is tracked by its unique employee ID. A plain button avoids a Web Forms server postback. If you add ng-cloak to your own application, spell it exactly and supply the associated cloak CSS in your stylesheet; the misspelled ng-cloack has no effect. This minimal page does not depend on cloak styling.

Step 3: Create employee-export.js

javascript
var app = angular.module("csvApp", ["ngSanitize", "ngCsv"]);
app.controller("MyController", ["$scope", function ($scope) {
    $scope.MyCSV = [{
      EmpId: 1001,
      EmployeeName: 'Nikunj Stasiya',
      Department: 'Information Technology',
      Designation: 'Sr.Software Engineer',
      City: 'Surat, India',
      ContactNo: '9*******24'
    },{
      EmpId: 1002,
      EmployeeName: 'Hiren Dobariya',
      Department: 'Information Technology',
      Designation: 'Sr.Software Engineer',
      City: 'Rajkot, India',
      ContactNo: '8*******96'
    },{
      EmpId: 1003,
      EmployeeName: 'Vivek Ghadiya',
      Department: 'Information Technology',
      Designation: 'Web Developer',
      City: 'Jamnagar, India',
      ContactNo: '7*******98'
    },{
      EmpId: 1004,
      EmployeeName: 'Milan lathiya',
      Department: 'Information Technology',
      Designation: 'Android Application Developer',
      City: 'Surat, India',
      ContactNo: '8*******77'
    },{
      EmpId: 1005,
      EmployeeName: 'Kishan Kotadiya',
      Department: 'Information Technology',
      Designation: 'Web Developer',
      City: 'Surat, India',
      ContactNo: '7*******53'
    },{
      EmpId: 1006,
      EmployeeName: 'Sarah Demola',
      Department: 'Information Technology',
      Designation: 'Software Engineer',
      City: 'California, USA',
      ContactNo: '7*******22'
    }];
    // Use arrays to make the CSV column order explicit in ng-csv 0.3.3.
    $scope.exportRows = $scope.MyCSV.map(function (employee) {
        return [employee.EmpId, employee.EmployeeName, employee.Department,
            employee.Designation, employee.City, employee.ContactNo];
    });
}]);

The six employee records are the original demonstration data, including masked contact numbers. MyCSV supplies the table; exportRows projects the same objects into six-element arrays. That projection makes the CSV order explicit without assuming that object enumeration will always match the header labels. If records change later, rebuild exportRows before exporting.

How the directive works

  • ngCsv is the AngularJS module dependency. ng-csv is the HTML directive. Neither dependency is named CSV.
  • ng-csv="exportRows" supplies the report data.
  • csv-header adds the six labels as the first record. It does not calculate an array difference or select object properties.
  • filename supplies the suggested download name; the browser controls where the file is saved.
  • charset="utf-8" selects the text encoding. It does not force a spreadsheet's delimiter, locale or column types.

Expected result and checks

Serve the folder over your development server, open the page and check that it shows six employees. Select Download CSV. The suggested filename is Codingvila_NikunjSatasiya_CSV.csv. In a CSV parser, expect seven records: one header plus six employees, with six fields in each. The comma in Surat, India must remain inside one City field.

If you see literal braces such as {{employee.EmpId}}, AngularJS has not compiled the template: check asset paths, the browser console, ng-app and the controller registration. A missing ngSanitize or ngCsv module prevents startup. A download with headings in the wrong order usually means the projected row order no longer matches the header array.

Security and migration limits

CSV escaping is not a spreadsheet formula defense. Treat untrusted text beginning with formula markers according to a tested export policy, and do not assume that sanitizing HTML makes a CSV safe in Excel. Do not export secrets or records the user is not authorized to view. This example holds all rows in browser memory and is intended for a small legacy report.

The controller projects the report into a fixed row shape, but that does not make the unsupported dependency stack suitable for a new production application. For ongoing development, plan a supported framework migration. The plain JavaScript exporter provides current browser download code, input validation, explicit CSV quoting and a discussion of spreadsheet-text handling without adding AngularJS to a new project.

Conclusion

The employee report now has an explicit six-column export order and a separate header row, while the table and download use the same sample data. Keep this pattern within the existing AngularJS maintenance context, test the resulting CSV with its real consumer, and use a supported application stack for new work. CSV supplies values and headers, not Excel workbook formatting.

About the author

Nikunj Satasiya

Software Engineer

Nikunj Satasiya writes practical tutorials on C#, ASP.NET Core, SQL Server, and Angular at Codingvila. He explains development workflows through focused code examples, clear reasoning, and troubleshooting guidance.

Pankaj profile image

How to get the excel data formatted the same way as on website?

Delete comment May 20, 2021 at 6:35:00 PM GMT+5:30

Join the discussion

Ask a question or share an implementation detail. Comments are reviewed before publication.