Giter Club home page Giter Club logo

vue-json-csv's Introduction

Vue JSON to CSV file

FOSSA Status NodeJs

VueJS component to export Json Data into CSV file and download the resulting file.

Example

GitHub Pages

Getting started

Get the package:

yarn add vue-json-csv

Register JsonCSV in your app entrypoint:

import Vue from 'vue'
import JsonCSV from 'vue-json-csv'

Vue.component('downloadCsv', JsonCSV)

In your template

<download-csv
    :data   = "json_data">
    Download Data
    <img src="download_icon.png">
</download-csv>

Props List

Name Type Description
data Array (required) Data to be exported
fields Array/Function(value, key) fields inside the Json Object that you want to export. If no given, all the properties in the Json are exported. Use the function to filter the data and only keep the properties you want.
labels Object/Function(value, key) Set the label for the header row.
name string filename to export, default: data.csv
delimiter string Default ",". Can be changed to anything.
separator-excel boolean If true, will prepend SEP={delimiter} to the file to make it easily usable with Excel
encoding string Set the wanted encoding, default to 'utf-8'
advancedOptions Object You can set all the options of PapaParse yourself

Example

import Vue from 'vue'
import JsonCSV from 'vue-json-csv'

Vue.component('downloadCsv', JsonCSV)

const app = new Vue({
    el: '#app',
    data: {     
        json_data: [
            {
                'name': 'Tony Peña',
                'city': 'New York',
                'country': 'United States',
                'birthdate': '1978-03-15',
                'phone': {
                    'mobile': '1-541-754-3010',
                    'landline': '(541) 754-3010'
                }
            },
            {
                'name': 'Thessaloniki',
                'city': 'Athens',
                'country': 'Greece',
                'birthdate': '1987-11-23',
                'phone': {
                    'mobile': '+1 855 275 5071',
                    'landline': '(2741) 2621-244'
                }
            }
        ]
    }
})

In your Template call it like

<download-csv
	class   = "btn btn-default"
	:data   = "json_data"
	name    = "filename.csv">

	Download CSV (This is a slot)

</download-csv>

REQUIRED

  • json_data: Contains the data you want to export

License

MIT

FOSSA Status

vue-json-csv's People

Contributors

ajohnson6494 avatar belphemur avatar codedavinci avatar dependabot[bot] avatar fossabot avatar hkd987 avatar jacksongross avatar kodiakhq[bot] avatar semantic-release-bot 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  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

vue-json-csv's Issues

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Seems to be broken on mobile Chrome for iOS

Using the example link here, and my own implementation, it does not download any file while using Chrome on iOS (Safari works fine). I tested using Chrome version 870.0.4280.163 (latest) and iOS 14.4.2. Anyone else have this issue?

Call Data computed property only when downloading

I noticed that the data proptery is being called on page load, as well as whenever the underlying data is updated. Is it possible to only call the computed property when actually downloading the file?

Give an example of the labels prop

Thanks for making this! First issues I encountered...
It's not clear as to what is expected when passing an object or what to return from a callback.

How to use plugin directly with script?

Can this plugin be used by using the script tag directly in page?

Example:


  <script src="/modules/vue/dist/vue.min.js"></script>
  <script src="/modules/vue-json-csv/dist/vue-json-csv.umd.min.js"></script>
  <script type="text/javascript"> Vue.use(downloadCsv)</script>

Array in Data not working properly

I am passing an object into the data prop that has the following structure:

Data: [
{
  data1: 'value',
  data2: ''value',
  dataArray: [
    {
      subData1: 'value',
      subData2: 'value',
      subData3: 'value'
    },
    {
      subData1: 'value',
      subData2: 'value',
      subData3: 'value'
    },
    ...
  ]
},
{
  data1: 'value',
  data2: ''value',
  dataArray: [
    {
      subData1: 'value',
      subData2: 'value',
      subData3: 'value'
    },
    {
      subData1: 'value',
      subData2: 'value',
      subData3: 'value'
    },
    ...
  ]
},
...
]

Based on this, the "dataArray" does not get parsed correctly.
In the CSV file, depending how many objects are in that array, it will just display [object Object].

The issue #66 offers a solution, but I do not see how that solution will help.

advancedOptions do not seem to be used

I have tried to use papa parse options like:

<download-csv
	class   = "btn btn-default"
	:data   = "results"  
       :advancedOptions ="{preview:2}"  
	name    = "planning.csv">

or as:

<download-csv  
	class   = "btn btn-default"  
	:data   = "results"  
       :advancedOptions ="opt"  
	name    = "planning.csv">  
(...)  
data :()=>({  
    opt:{preview:2}  
})

But it does not break after 2 lines. How should i use these advancedOptions?

Vue 3 compatibility?

Hi there

I was wondering if there were any plans to make this compatible with Vue 3?

I installed it and it doesn't work with Vue 3, however, I simply copied over the src file and used it instead of this package which works. Therefore it's probably a small change to convert it to be Vue 3 friendly.

"separator-excel=true" and "encoding=utf-8" prevent BOM to work

Hello,

I'm using version 1.2.10, and I have a strange behaviour....

When trying to export using separator-excel=true and encoding set to encoding=utf-8, then I have the encoding being set like without BOM.

As a workaround, I've set the delimiter to ";" and removed separator-excel=true.
I think it's probably an Excel problem more than a "vue-json-csv" problem, but I don't know...

So I hope that it will at least help some people having this issue.

Failed to compile after upgrading to version 1.2.8

Hi again,
thanks for fixing my encoding issue #23 so quickly. I just upgraded from version 1.2.5 to 1.2.8. However I was not able to try it yet as it fails to compile. I get this error message:

Failed to compile.

./node_modules/vue-json-csv/dist/vue-json-csv.common.js
Module parse failed: Unexpected token (17562:8)
You may need an appropriate loader to handle this file type.
|         delimiter: this.delimiter,
|         encoding: this.encoding,
|         ...this.advancedOptions
|       })
|       if (this.separatorExcel) {
 @ ./node_modules/babel-loader/lib??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./app/javascript/src/shared/startlists/lead/lead_startlist.vue?vue&type=script&lang=js& 48:0-35
 @ ./app/javascript/src/shared/startlists/lead/lead_startlist.vue?vue&type=script&lang=js&
 @ ./app/javascript/src/shared/startlists/lead/lead_startlist.vue
 @ ./node_modules/babel-loader/lib??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./app/javascript/src/judges/dashboard/index.vue?vue&type=script&lang=js&
 @ ./app/javascript/src/judges/dashboard/index.vue?vue&type=script&lang=js&
 @ ./app/javascript/src/judges/dashboard/index.vue
 @ ./app/javascript/packs/judges/dashboard/index.js
 @ multi (webpack)-dev-server/client?http://localhost:3035 ./app/javascript/packs/judges/dashboard/index.js

File ./app/javascript/src/shared/startlists/lead/lead_startlist.vue is of course the file where I use JsonCSV. I did not change anything else, only updated your package, and used not to get this error in 1.2.5.
If you could help me, it would be very appreciated.
Let me know if you need further info.
In the meantime I'm downgrading to 1.2.5 for development purposes.

Thank you in advance.

No data to export

Hi everyone

Download not working.

My code:
HTML

<download-csv
       @click="exportGraph"
       class="btn btn-success"
       :data="wellsExporteds"
       name="Lista de Poços.csv"
     >Exportar Póleo</download-csv>

SCRIPT

<script>
import exportCsv from "../plugins/exportCsv";

methods: {

async exportGraph() {
      let exportWellId = new Array();

      exportWellId.push(this.idwell);

      const exportPoil = axios.create({
        withCredentials: true
      });
      exportPoil
        .post("http://localhost:8000/gerenciamento/ExportarPoleo", {
          well_ids: exportWellId
        })
        .then(response => {
          this.wellsExporteds = response.data;
          console.log(this.wellsExporteds);
        });
    }
}
</script>

NUXT CONFIG
plugins: ["~/plugins/main.js", "~/plugins/exportCsv.js"],

TypeError

Uncaught (in promise) TypeError: Cannot read properties of null (reading 'isCE'), What is the cause of this problem?

Cannot read properties of undefined (reading 'call')

Firstly thanks for creating this library, but ive just tried to implement it and im getting the following console error:

vue-json-csv.common.js?2347:5361 Uncaught TypeError: Cannot read properties of undefined (reading 'call')

The vue application builds fine.

Asset compilation fails in v1.2.7

Our builds were failing with the following error during asset compilation. This happens with 1.2.7 and does not happen in 1.2.5.

ERROR in ./node_modules/vue-json-csv/dist/JsonCSV.js
Module not found: Error: Can't resolve 'vue-runtime-helpers/dist/normalize-component.js' in '/var/lib/jenkins/jobs/project/workspace/node_modules/vue-json-csv/dist'
@ ./node_modules/vue-json-csv/dist/JsonCSV.js 8:40-98
@ ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?

The computed property "fields" is already defined as a prop.

Hi,
First of all, great work! :)

I have some custom console error (vue warn - The computed property "fields" is already defined as a prop).
Plugin imported:
import JsonCSV from "vue-json-csv";

Then I defined component inside my component like this:
downloadCsv: JsonCSV

After that I'm using downloadCsv component in v-for loop inside table td:
<download-csv :data="[row.data]" :name="${row.name}.csv"> <i class="material-icons">cloud_download</i> </download-csv>

row.data is object.
row.name - using template literals

It will be great if you provide some answer. Thanks.

csv as matrix

hi @Belphemur !
I wonder how to achieve the proper format of my extracted csv to be displayed as a matrix, let's say a 2 by 2 like so :

label 1 label 2
label 1 1 0
label 2 0 1

I cannot let the first cell empty

;;label 1;label 2;
;label 1;1;0;
;label 2;0;1;

labels function not called

Template

<JsonCSV
      :data="json_data"
      :fields="getCSVFields"
      :labels="getCSVLabels"
    >
Download
    </JsonCSV>

Code:

import JsonCSV from "vue-json-csv";

export default {
  components: {
    JsonCSV
  },
  data() {
   json_data: [
            {
                'name': 'Tony Peña',
                'city': 'New York',
                'country': 'United States',
                'birthdate': '1978-03-15',
                'phone': {
                    'mobile': '1-541-754-3010',
                    'landline': '(541) 754-3010'
                }
            },
            {
                'name': 'Thessaloniki',
                'city': 'Athens',
                'country': 'Greece',
                'birthdate': '1987-11-23',
                'phone': {
                    'mobile': '+1 855 275 5071',
                    'landline': '(2741) 2621-244'
                }
            }
        ]
    }
}
  },
  methods: {
    getCSVFields: function(value,key)
    {
//console.log in here gets called fine
      if (key == 'groupColor')
      {
        return false
      }
      return true;
    },
    getCSVLabels: function(value,key)
    {
      console.log('getCSVLabels',value,key)
//this doesn't show in my console
      return key+value;
    }
  }
}

No TS

There is not Typescript support for Vue 3

Could not find a declaration file for module 'vue-json-csv'.

This is not an issue

I just had no place leave a comment so I am using this as the only place. I apologize in advance. I am just pretty impressed with how easily this package integrated with my Vue app. A true plug and play. Big props!

Version 1.2.10 breaks in IE11

Recently I accidentally upgraded from version 1.2.4 to 1.2.10. I realize this version is not yet on here, but it is on npm. It breaks in IE11 on this:

advancedOptions: { type: Object, default: () => { } }

IE doesn't understand () => { }

Allow for Async Data Requests

I was curious if this is a use case you've used in the past and if there's already a solution for it. My new feature requires an axios call to be fired to grab results from our backend upon click; we would like to export those results to CSV using this library. The issue is that the export is executed immediately upon click, with seemingly no way to force the component to wait for the request to return with the correct data from the back end (apart from sending that request every time the page loads, which isn't ideal). Any thoughts?

encoding problem

i have set endoing='utf-8' ,but when export , the file still does not display the chinese font, any idea?

<download-csv class="text-black" :data="this.jsonData" name="BookInfo.csv" encoding="utf-8"> Export </download-csv>

jsonData: [{ 'name': '你好', 'city': 'New York', 'country': 'United States', 'birthdate': '1978-03-15', 'phone': { 'mobile': '1-541-754-3010', 'landline': '(541) 754-3010' } }, { 'name': 'Thessaloniki', 'city': 'Athens', 'country': 'Greece', 'birthdate': '1987-11-23', 'phone': { 'mobile': '+1 855 275 5071', 'landline': '(2741) 2621-244' } } ],

`vue-json-csv >=1.2.11` depends on vulnerable version of `lodash.pick`

lodash has had an issue with prototype pollution. vue-json-csv should update its dependencies to not use the affected versions, otherwise users will potentially be exposed to severe vulnerabilities when using the package.

While vue-json-csv is slightly more convenient, I was able to replace vulnerable vue-json-csv completely by using json-2-csv and techniques in this post:

<v-btn prepend-icon="mdi-download" @click="downloadFile"></v-btn>

import * as converter from "json-2-csv";

function downloadFile() {
// downloadableJSON: Record<string, string | number>[]
  const csv = converter.json2csv(downloadableJSON);
  const anchor = document.createElement("a");
  anchor.href = "data:text/csv;charset=utf-8," + encodeURIComponent(csv);
  anchor.target = "_blank";
  anchor.download = "resultsData.csv";
  anchor.click();
}

How to be download button disabled

download-csv
:data = csvData
class= "vs-component vs-button mb-4 vs-button-success vs-button-filled"
:disabled="isDisabled"
>
Download
/download-csv

isDisabled: true

problem with cyrillic

Hello, thank u for this component. But i have a problem with cyrillic symbols. Its look terrible in MS Excel. Like this

44,�>4@O4G8:,,�>=AB0=B8=>20 �235=8

Documentation example 'fields

First of all, thanks for this great plugin !
I am struggling to understand how to use 'fields' to access nested properties or to modify the value of the property
Could you please clarify how it is supposed to be used ?
I tried to use it like this but my exported file is empty

labels: {
    'id': 'ID',
    'createdAt': 'Date',
    'product': 'Title',
},
fields: {
  'createdAt':  (value) => {
   this.dateTimeFormat(value);
  },
  'product':  (value) => {
    value.title;
  },
}

typeError

hi, I try to follow your example for Vue 3 but I get the following error message:

runtime-core.esm-bundler.js:38 [Vue warn]: Unhandled error during execution of render function
at <JsonCSV data= (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}] name="my_export.csv" >
at

runtime-core.cjs.js:6504 Uncaught TypeError: Cannot read properties of null (reading 'isCE')
at renderSlot (runtime-core.cjs.js:6504:34)
at Proxy.render (JsonCSV.vue?a4ce:13:5)
at renderComponentRoot (runtime-core.esm-bundler.js:893:44)
at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js:5045:57)
at ReactiveEffect.run (reactivity.esm-bundler.js:185:25)
at setupRenderEffect (runtime-core.esm-bundler.js:5171:9)
at mountComponent (runtime-core.esm-bundler.js:4954:9)
at processComponent (runtime-core.esm-bundler.js:4912:17)
at patch (runtime-core.esm-bundler.js:4504:21)
at mountChildren (runtime-core.esm-bundler.js:4700:13)

App.txt

How to generate csv from a function?

Hi, I have a button "Download" which will call an api to fetch data and then export that data to CSV. But I could not find how to do it with this package. it looks like we need to have a json data before clicking download button

problem with accent

Since you upgrade i got some problem with accent and special character for exemple Référent become Référent
I check and it is 'encoding:"utf-8";
Do you have any idea please ?

THanks a lot in advance

encoding option seems to be not working

Hi, thx for the great library. :)
I'd like to export csv file on Shift_JIS format and implemented as below.

    <download-csv
      :data = "data"
      encoding = "shift_jis"
    >

I also tried the values such as "shiftjis", "shift-jis" and "sjis" but none of them worked.
It just gives me a csv with utf-8.
There may be something wrong with my way of implementation.
If it's the case, would you tell me the way to indicate the encoding format?
I looked through the docs but can't figure it out...
Thx,

Nested objects

Hello,

I'm trying to export an object that has a nested object, but when I do, the values for that column appear as [object Object].

Encoding problems

Hi,
first of all thanks for the great work!

I think I am experiencing some issues with encoding.
I have this data that I pass to JsonCSV:

data = [{
order: 37
lastname: Širůčková
firstname: Tereza
}]

and I expect the downloaded csv to contain:

order,lastname,firstname
37,Širůčková,Tereza

but instead I get this output:

order,lastname,firstname
37,`iro
ková,Tereza

Encoding is set to default (utf8). I tried changing it to utf16 to no avail. Anyway I don't think that's the issue, as I use another tool to generate pdf files with encoding set to utf8 and have no problem. I did not notice similar behaviour with other characters so far. Is it a known issue? Is there a fix for this? If you could point me in the right direction it would be highly appreciated.

Thank you in advance

v1.2.12 broke support for IE 11

I utilize vue-json-csv in an enterprise application where I have to support Internet Explorer 11 🤮 . Based on the settings added in v1.2.12, Internet Explorer 11 can no longer utilize the package.

I'm just guessing here, but I believe it's because of the browserslist entry in package.json. In my Vue app, I have my own .browserlistrc file with the following contents:

> 3%
last 3 versions
not ie < 11

Unsure of what the actual setting would be here, but if you could restore support for Internet Explorer 11 for us enterprise users, that would be much appreciated!

Option for dynamic file name

Lovely package that was easy to get up and running.

I'd like to have a dynamic file name that interpolates the date, and perhaps some other variables.
If I had a method to call I could do it there, but I currently only see an option to add this in-template.

Am I mistaken, or is there a workaround to generate a dynamic file name?

How change filename after click download

Hello. Thank you for your library.
How I can generate filename after click button?

<download-csv
  :data=fraudErrorsForCSV
  :name="CSVFileName"
  ref="export"
  hidden
>
</download-csv>

<v-btn
  color="green"
  rounded
  @click="createFileName">
  Errors(csv)
</v-btn>

createFileName () {
      var currentdate = new Date()
      this.CSVFileName = `log_${currentdate.getDate()}-${currentdate.getMonth()}-${currentdate.getFullYear()} ${currentdate.getHours()}-${currentdate.getMinutes()}-${currentdate.getSeconds()}.csv`
      this.$refs.export.generate()
    },

data () {
return {
CSVFileName: null,
....
}

Downloaded CSV files don't open on mobile / tablet

File seems to download OK, but when opening I get a "can't open file" error.

The files seem to still show in "blob" format when downloaded. Not sure if that's an issue.

Tested on Android Chrome so far.

image

Downloading as xlsx doesn't work

Title says it all, I tried every combination to download my data to .xlsx (do not want xls) and no dice, maybe this isn't a feature? Would be cool if there was a way, it makes it easier for users to get excel data and not have to convert from csv

Undefined Error

Getting the following error, just loading the website. Not even pressing the download button. I was previously using vue-json-excel with no issues. Any ideas?
Uncaught TypeError: Cannot read properties of undefined (reading 'call')
at webpack_require (vue-json-csv.common.js?2347:5361:1)
at eval (vue-json-csv.common.js?2347:5465:1)
at eval (vue-json-csv.common.js?2347:5732:1)
at eval (vue-json-csv.common.js?2347:5734:1)
at ./node_modules/vue-json-csv/dist/vue-json-csv.common.js (chunk-vendors.js:5238:1)
at webpack_require (app.js:854:30)
at fn (app.js:151:20)
at eval (cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/base/_base-widget-system-bar.vue?vue&type=script&lang=js&:47:71)
at ./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/base/_base-widget-system-bar.vue?vue&type=script&lang=js& (app.js:1643:1)
at webpack_require (app.js:854:30)

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.