Git Product home page Git Product logo

angular2-csv's Introduction

Angular2-csv | Export to CSV in Angular6

Helper library for create CSV file in Angular 6

Installation

npm install --save angular2-csv

For Angular [ 2,4,5 ] install old version:

npm install --save angular2-csv@0.2.5

Example

Add module in app.module.ts

import { Angular2CsvModule } from 'angular2-csv';

Add in imports section

imports: [
  BrowserModule,
  Angular2CsvModule
],

Use in component

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  options = {
    fieldSeparator: ',',
    quoteStrings: '"',
    decimalseparator: '.',
    showLabels: false,
    headers: [],
    showTitle: true,
    title: 'asfasf',
    useBom: false,
    removeNewLines: true,
    keys: ['approved','age','name' ]
  };
  data = [
    {
      name: "Test, 1",
      age: 13,
      average: 8.2,
      approved: true,
      description: "using 'Content here, content here' "
    },
    {
      name: 'Test 2',
      age: 11,
      average: 8.2,
      approved: true,
      description: "using 'Content here, content here' "
    },
    {
      name: 'Test 3',
      age: 10,
      average: 8.2,
      approved: true,
      description: "using 'Content here, content here' "
    }
  ];
}

In template

<angular2csv [data]="data" filename="test.csv" [options]="options"></angular2csv>

API - Angular2Csv(data, filename, options)

Option Default Description
fieldSeparator , Defines the field separator character
quoteStrings " If provided, will use this characters to "escape" fields, otherwise will use double quotes as deafult
decimalseparator . Defines the decimal separator character (default is .). If set to "locale", it uses the language sensitive representation of the number.
headers [] If provided, would use this attribute to create a header row
showLabels false If provided, would use this attribute to create a header row
showTitle false
title filename Csv title
useBom true If true, adds a BOM character at the start of the CSV
removeNewLines false If true, remove new lines from columns (Helps to remove special characters that can't recognized)
keys [] If provided, would use this attribute to have an order of columns

Example

  var options = {
    fieldSeparator: ',',
    quoteStrings: '"',
    decimalseparator: '.',
    headers: ['column 1 header', 'column 2 header'],
    showTitle: true,
    useBom: true,
    removeNewLines: false,
    keys: []
  };

angular2-csv's People

Contributors

ahmed-anas avatar alexbjorlig avatar arf1980 avatar christianguevara avatar gavriln avatar gtzinos avatar hukacode avatar javiertelioz avatar jesussobrino avatar jmann-tw avatar makotoishida avatar sn123 avatar stevenmcountryman avatar sujeethaganesan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

angular2-csv's Issues

Pb in chrome, IE & Edge Exporting large text/CSV -> crash download

I found a solution to this issue -> use Blob for all browsers :

Angular2Csv.prototype.generateCsv = function () {
    this.csv += CsvConfigConsts.BOM;
    if (this._options.showTitle) {
        this.csv += this._options.title + '\r\n\n';
    }
    this.getHeaders();
    this.getBody();
    if (this.csv == '') {
        console.log("Invalid data");
        return;
    }
    **var blob = new Blob([this.csv], { "type": "text/csv;charset=utf8;" });**
    var filename = this._options.filename.replace(/ /g, "_") + ".csv";
    if (navigator.msSaveBlob) {
        navigator.msSaveBlob(blob, filename);
    }
    else {
        var link = document.createElement("a");
        **link.href = URL.createObjectURL(blob);**
        link.setAttribute('visibility', 'hidden');
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
};

Can you please update the module angular2-cvs with those changes ?

This library is one and done. Cannot creat multiple .csv file quickly or in succession. Can permenantly stop working.

Browser: Chrome Version 61.0.3163.100 (Official Build) (64-bit)

A simple promise chain making three separate api calls and giving the data back as CSV can only create a CSV from the first api call. Subsequent calls to new Angular2Csv() return no files. This sample code will stop all future calls to Angular2Csv from returning any csv files.

this.driverService.getWiringTests()
            .then((res) => {
                const options = {
                    showLabels: true,
                    showTitle: false,
                    headers: Object.keys(res[0])
                };
                new Angular2Csv(res, 'WiringTestResults', options);
                new Angular2Csv(res, 'WiringTestResults', options);
            })

In fact any button that generates a CSV that is clicked quickly will shut this library down entirely making it unable to generate any more CSV's until the page is refreshed. Consider a refactor.

Live Demo?

The project has a live demo available right now?. You could give us the link for this?

Thanks. :)

404 after install

During install I received these warnings:

[email protected] C:\Source\RLSupply\RedLobster.RLSupply.WebClient
`-- [email protected]

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\br
owser-sync\node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}
)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\ch
okidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}
)

When I run the application it stops and the console logs this error

Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:3276/angular2-csv/Angular2-csv
Error loading http://localhost:3276/angular2-csv/Angular2-csv as "angular2-csv/Angular2-csv" from http://localhost:3276/app/home/home.component.js

Excel All data in first Column

Hi,

Sometimes, on different machines with the same version of Excel, the data is not showing correctly. Its all shown in the first column with the separators:
v1

Any idea how to fix this?

Thank you.

Headers missing in v0.2.5

Hi,

We are working for this library for a while now.
Using v0.2.3 all worked perfectly. one npm install updated the version to v0.2.5 and headers were missing.
the data inserted to Angular2CSV constructor was an object and the keys wasn't placed as headers.

Please check it. Thanks

unable to generate header row

I am trying to create a CSV file that has a header row, and download that to the users machine. I pass in the array and use JSON.stringify() and that gets me back my JSON string. I have been able to create the file and then download it on request, however it doesnt include the headers.
Here is the code i am using, i am hoping that someone can help out.

here is the code that creates the CSV and binds it to the '(click)' attribute on the download button:

downloadCsvFile(exportedData: IExportDataObject[]) { //creates the JSON string from the array of object. let exportedDataJson = JSON.stringify(exportedData); //creates the options variable specified in the documentation var options = { fieldSparator: ',', quoteStrings: '"', showLabels: true } //calls the method to create the CSV new Angular2Csv(exportCorrCodesJson, 'ExportedCorrectionCodes', options); }

here is my IExportDataObject format when it is "Stringified":

[{"id":8029017,"pgm_code_name":"FAS","rgln_Year":"2015","rgln_type_name":"IMC","rgln_one_code":"1007 ","rgln_two_code":" ","rgln_three_code":"","rgln_title_text":"BOILER LOW-WATER CUTOFF","rgln_desc_text":"","sevrty_code":null,"valdtn_value":"Production","last_updt_dt":"2017-08-26T09:04:39.287","last_updt_logn_id":"USER235","prev_rec_id":null}]

What i am getting when i open the file is an excel sheet that only has the values for each column, not the names.

Thank you in advance for any help

data area passed to a system call is too small

On IE Browser there is this error while creating CSV: "data area passed to a system call is too small".
I Think this is due to the creation of the element "a" in the html. Href is the whole csv content and this is too long for IE

Open button not present in IE 11

I have the following Angular 4 code which is used to export data to csv

export() {
   
    let exportResults: any[] = [];
    
    var options = {
      fieldSeparator: ',',
      showLabels: true
    };
    this.myService.export(input).subscribe(
      (response: Response) => {
        exportResults = JSON.parse(response.text());
        new Angular2Csv(exportResults, 'Exported Data', options);
      },
      (error) => {
        console.log(error)
      }
    )
  }

This code exports the data to csv as expected, however in IE11, it does not show the 'Open' button. It does have 'Save', 'SaveAs' and 'Cancel' options though.

I do realize that this pop out is shown by IE so we don't have much control over it. However, I have seen 'Open' button displayed in IE11 when downloading files. So wanted to check if there is something that we can do to get the Open button.

decimalseparator

For some reason I cannot set the decimal seperator to ",".

I guess it's quite common to use "," as decimal separator when using ";" as separator?

Do not download the csv in the class Constructor itself.

I see in the README.md file that the way to download the csv is olny by creating an instance of the Angular2Csv Class, and inside the constructor, it is called a private generateCsv() function to downlod the file. It causes sometimes unassigned objects and you can't decide at what specific time to generate the file, for example:

onClickDownload() {
new Angular2Csv(this.data, 'My_report', options);
}

This generates inmediatly the csv file, maybe someone will need to generate this file in other different moment.

I think that can be a best practise to declare generateCsv() as a public function inside the class and consume this function where necessary, separating the constructor's responsibility:

(Code after refactor)

onClickDownload(): void {
const csvFile = new Angular2Csv(this.data, 'My_report', options);
csvFile.generateCsv();
}

Greetings

How to set labels

When using this tool, data is exporting just fine. I want to show labels of what each column represents. I see in the documentation that I can set showLabels:true in the options. This did not work for me. How do I set labels?

Transform data which is complex and not string?

For Example, if I give

data = {
"key1": "value1",
"key2": ["value2", "value3"],
"key3": "value4",
}

If there a way to get the below. This would ensure that the headers belong to the specific columns

value1, value2 value3, value4

or

value1, "value2 value3", value4

More precisely, If its an Array of Objects, return them as String space-separated.

Currently, I am getting below mentioned - which kinda skews columns.

value1, value2, value3, value4

Using Options to do this would be helpful

Angular 5

Could you please update the dependencies to allow angular5 as well?
I believe that no functional changes are required

Date formatting

How can a JSON date be formatted to render properly in the csv?

2018-03-11T07:00:01.053 needs to be 03/11/2018 07:00 AM

The BOM characters cause issue in Excel 2016

Maybe make the BOM character configurable as well?
I found that after adding it, Excel 2016 will incorrectly treat the file as text file.
After opening the file in Excel 2016 and saving it directly, Excel will replace all the comma to tab, this will cause issue if user wants to edit the downloaded csv file.

Can't install package with npm

Hi,
I am getting the following errors:

-- [email protected]

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"
})
npm WARN enoent ENOENT: no such file or directory, open '<project_path>\node_modules@angular\material\package.json'
npm WARN [email protected] requires a peer of @angular/core@~2.0.0 but none was installed.
npm WARN [email protected] requires a peer of @angular/common@~2.0.0 but none was installed.
npm WARN [email protected] requires a peer of @angular/compiler@~2.0.0 but none was installed.
npm WARN [email protected] requires a peer of @angular/platform-browser@~2.0.0 but none was installed.
npm WARN [email protected] requires a peer of @angular/http@~2.0.0 but none was installed.
npm WARN [email protected] requires a peer of zone.js@~0.6.13 but none was installed.

Can someone help?

Removal of import { Angular2Csv } from 'angular2-csv/Angular2-csv';

Thanks for the great library on the recent release you decided to remove a valid use case of constructing an csv export via function.

report() {
return new Angular2Csv(items, report, options);
}

What was the reason behind this and would you re-add this functionality or did i just miss where it moved?

Network Error

Hi,

I have been using this module to download upto 5000 rows from my application in a CSV of 860Kb and it works great.
But now I am trying to increase that to 10,000 and I get an error "Failed - Network Error" in chrome (works fine for IE). Is there a limit to the number of records or the size of the file that can be downloaded via chrome?

How to separate data in columns

How to i can separate data in columns
i currently downloading data in csv format, but i need open file in spreadsheet but i didnt not make it

angular cli 6

When run ng build --prod gives back an error

Angular2-csv.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.?

This library is framework-agnostic

While looking at the source code I cannot see any uses of the Angular here.
However, in the package.json dependencies are listed. What is their purpose?
I feel that the library should be named "JSON to CSV" which is much closer to the truth.

All headers adds to one cell

I have headers option:

{ headers: ['column 1 header', 'column 2 header'] }

But in file both headers are added to the same cell:
image

Unable to Export CSV in safari

Hi

Unable to export data in safari instead it shows raw data in browser.

Safari version: 10.0.1

Is there any fix to this...

Regards

Kailash

Unable to install

npm ERR! 404 Registry returned 404 for GET on https://registry.npmjs.org/Angular2-csv
npm ERR! 404
npm ERR! 404 'Angular2-csv' is not in the npm registry.
npm ERR! 404 Your package name is not valid, because
npm ERR! 404 1. name can no longer contain capital letters
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

Version Numbering Details

Hi, firstly thank for such great library. I just wanted to let you know that the recent changes you had made had a breaking impact on our application which was using this library.

I always thought the major version number changes when there is a large change, in this case upgrade to version 6. It would be good if the package version had changed to 1.0.0 :) anyways, just my thoughts 👍

I want multi row for header

So, I modified the source.

  1. interface Options add => multiHeader: boolean;

  2. public static DEFAULT_MULTI_HEADER = false;

  3. ConfigDefaults: Options add => multiHeader: CsvConfigConsts.DEFAULT_MULTI_HEADER,

getHeaders(): void {
if (this._options.multiHeader) {
for (var i = 0; i < this._options.headers.length; i++) {
if (this._options.headers[i].length > 0) {
let row = '';
for (let column of this._options.headers[i]) {
row += column + this._options.fieldSeparator;
}
row = row.slice(0, -1);
this.csv += row + CsvConfigConsts.EOL;
}
}
} else {
if (this._options.headers.length > 0) {
let row = '';
for (let column of this._options.headers) {
row += column + this._options.fieldSeparator;
}
row = row.slice(0, -1);
this.csv += row + CsvConfigConsts.EOL;
}
}
}

Working with an Array of heterogeneous data

I have an array that contains heterogeneous data, ie each object might not have all the keys. Some may be optional. The exported columns are misplaced considering the headers in this case. Anyone had such experience?

When I am trying to install the package it shows me an error

npm ERR! Windows_NT 10.0.10586
npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "install" "--save" "Angular2-csv"
npm ERR! node v6.9.5
npm ERR! npm v3.10.10
npm ERR! code E404

npm ERR! 404 Registry returned 404 for GET on https://registry.npmjs.org/Angular2-csv
npm ERR! 404
npm ERR! 404 'Angular2-csv' is not in the npm registry.
npm ERR! 404 Your package name is not valid, because
npm ERR! 404 1. name can no longer contain capital letters
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! Please include the following file with any support request:
npm ERR! C:\angular\hello\npm-debug.log

import { Angular2CsvModule } from 'angular2-csv'; not working v0.2.5

Hi, Thanks a lot for this package, I have readed the documentation about that and this is very clear. However, when I try install it, the Angular2CsvModule isn't accepted. it's an import error. In my npm packege exist angular2-csv packege. I don't undersntad what happen. Is The install for 0.2.5 version different to current version?.

My angular version current is 5.0

Returns only new lines

Data format I use:

[
    {
        firstColumn: "column1"
        secondColumn: "column2"
        thirdColumn: "column3"
        fourthColumn: "column4"
    }
]

Code I use to generate csv:
new Angular2Csv(exportData, 'report')

Here is object of Angular2csv in console:

Angular2Csv {csv: ↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵", 
data: Array(37), _options: {…}}
csv:"↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵"
data:(37) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
_options:
{filename: "report", fieldSeparator: ",", quoteStrings: """, decimalseparator: ".", showLabels: false, …}

P.S. If I use headers, then headers are written to csv, but data is not.

Build Error.

Good evening, i have a problem when i building my application with the command 'ng build --prod --aot'.
The CLI show this error: 'Cannot find module 'angular2-csv/Angular2-csv' '. I've import the Angular2Csv in my component.

How to convert only required properties of JSON Array to csv

var data = [ { name: "Test 1", age: 13, average: 8.2, approved: true, description: "using 'Content here, content here' " }, { name: 'Test 2', age: 11, average: 8.2, approved: true, description: "using 'Content here, content here' " }, { name: 'Test 4', age: 10, average: 8.2, approved: true, description: "using 'Content here, content here' " }, ];

If I don't want to convert age property to csv. Is there any way?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.