7

I'm using Angular v4, i guess how can I build an Excel spreadsheet starting from an object in a component. I need to download the Excel file on the click of a button and I have to do this client side. I have a json file composed of arrays and I need to transfer this on an excel file, possibly customizable in style. Is it possible? If yes, how?

Edit: No js libraries please, need to do this with Typescript and Angular

4

4 Answers 4

19
+50

yourdata= jsonData

ConvertToCSV(objArray) {
            var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
              var str = '';
            var row = "";

            for (var index in objArray[0]) {
                //Now convert each value to string and comma-separated
                row += index + ',';
            }
            row = row.slice(0, -1);
            //append Label row with line break
            str += row + '\r\n';

            for (var i = 0; i < array.length; i++) {
                var line = '';
                for (var index in array[i]) {
                    if (line != '') line += ','

                    line += array[i][index];
                }
                str += line + '\r\n';
            }
            return str;
        }

in your html:

<button (click)="download()">export to excel</button>

in component:

download(){    
 var csvData = this.ConvertToCSV(yourdata);
                        var a = document.createElement("a");
                        a.setAttribute('style', 'display:none;');
                        document.body.appendChild(a);
                        var blob = new Blob([csvData], { type: 'text/csv' });
                        var url= window.URL.createObjectURL(blob);
                        a.href = url;
                        a.download = 'User_Results.csv';/* your file name*/
                        a.click();
                        return 'success';
}

Hope you it will help you

2
  • Hello paruvelly, I am using your code, the file is downloaded successfully but can't open in excel sheet. Error - Can't open file This version of office can't support the file. Do you have any idea why such error is coming? Any help will be appreciated.
    – TechValens
    Commented Jan 29, 2019 at 11:05
  • does anyone knows how to add custom header other that the json value as header? Commented Oct 16, 2022 at 15:13
1

Vishwanath answer was working for me when i replaced "," with ";". In Typescript the implementation could look like this:

ConvertToCSV(objArray: any) {
    const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
    let str = '';
    let row = '';

    for (const index of Object.keys(objArray[0])) {
      row += `${index};`;
    }
    row = row.slice(0, -1);
    str += `${row}\r\n`;

    for (let i = 0; i < array.length; i++) {
      let line = '';
      for (const index of Object.keys(array[i])) {
        if (line !== '') {
          line += ';';
        }
        line += array[i][index];
      }
      str += `${line}\r\n`;
    }
    return str;
  }

I hope this helps someone.

0

I think you will not get that done without js libraries in the background. What you need are the typings for utilizing it in your Angular project with typescript.

For creating an excel file you could use something like exceljs. To use it in your project also install the typings you can find here. I am not sure if this library fits... haven't used it before.

For downloading you should use FileSaver.js (I have already used it).

npm install file-saver --save

... and the typings:

npm install @types/file-saver --save-dev

For using FileSaver.js put the following import to your component:

import * as FileSaver from 'file-saver';

To trigger the download use that:

FileSaver.saveAs(fileData, "filename.xlsx")

'fileData' has to be a Blob.

Hope this helps a little.

1
  • Vishwanath's code works just fine, with the changes mentioned by user3588429. It's simple and effective, without the need for JS libraries
    – Maverik
    Commented Nov 12, 2020 at 13:01
-2

it not is possible.

XLS is a binary format.

The project Apache POI(https://en.wikipedia.org/wiki/Apache_POI) name class as HSSF (Horrible SpreadSheet Format).

my recommendation, make it in server side.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.