Generate / download a CSV file with Ionic


#1

I’ve just spent a few hours trying to work out exactly how I can convert a JSON array into a CSV file which the user can save to their phone. The use case for this scenario is as follows:

  • User opens App
  • App displays results from a noSQL database as an ion-list
  • User wishes to save this data as a CSV, thereofre clicks the “Download to CSV” button
  • App generates CSV file and saves it in the “Downloads” directory of the phone

I assumed this would be a reasonably common scenario, however I have been unable to find any sample code online. I’ve searched the Ionic forums and found a few people asking the same question for Ionic 1, but none of these had solid answers and it didn’t seem like anyone else has asked the question for Ionic 2.

I managed to write a javascript function to convert a JSON object to a CSV file, however this only works in my browser (Chrome) and not on my Android device.

Do I need to use Native plugins like the File Plugin? I’m finding the documentation there a bit ‘thin’ to follow.

Does anyone have a working example of the functionality I require?


#2

Do you have any news here?


#3

Unfortunately not, I ended up abandoning the idea as I didn’t receive any response from the community and I couldn’t solve the problem myself. I would still love to know the answer :slight_smile:


#4

I managed it working with this (imported the File-plugin before):

saveAsCsv() {
    var csv: any = this.convertToCSV(this.team.teams)

    var fileName: any = "team.csv"
    File.writeFile(File.externalRootDirectory, fileName, csv, true)
      .then(
      _ => {
        alert('Success ;-)')
      }
      )
      .catch(
      err => {

           File.writeExistingFile(File.externalRootDirectory, fileName, csv)
          .then(
          _ => {
        alert('Success ;-)')
          }
          )
          .catch(
          err => {
            alert('Failure')
          }
          )
      }
      )

  }

  convertToCSV(teams) {
    var csv: any = ''
    var line: any = ''

    var SpT = teams[0].length
    var anzahlTeams = teams.length

    //Header
    for (var i = 0; i < anzahlTeams; i++) {
      if (line != '') line += ';'
      line += "Team " + (i + 1)
    }
    csv += line + '\r\n';

    //Teams
    for (var i = 0; i < SpT; i++) {
      line = ''
      for (var j = 0; j < anzahlTeams; j++) {
        if (line != '') line += ';'
        
        line += teams[j][i]
        
      }
      csv += line + '\r\n'
    }

    return csv
  }

Hope this helps you :wink:


#5

working fine but its not showing any download notification how come any one know where to look for file …


#6
 convertToCSV(teams) {
    var csv: any = ''
    var line: any = ''

    var SpT = teams[0].length
    var anzahlTeams = teams.length

    //Header
    for (var i = 0; i < anzahlTeams; i++) {
      if (line != '') line += ';'
      line += "Team " + (i + 1)
    }
    csv += line + '\r\n';

    //Teams
    for (var i = 0; i < SpT; i++) {
      line = ''
      for (var j = 0; j < anzahlTeams; j++) {
        if (line != '') line += ';'
        
        line += teams[j][i]
        
      }
      csv += line + '\r\n'
    }

    return csv
  }

Do you have something like above for pdf ?


#7

Just recently I created a full tutorial on How to Parse, Visualise and Export CSV Data with Ionic, perhaps this helps and shows a concept to transform the data!


#8

Thanks for the tutorial! It works fine with the local file.
In the next step I wanted to fetch a local file from the android system with the filechooser plugin. I’m getting the uri from the file-chooser plugin, which I load instead of the local file path of the tutorial. Unfortunately the script throws an error when loading the file.

{_body: "", status: 404, ok: false, statusText: "Not Found", headers: Headers…}

This seems to come from a cross origin problem. I also tried to get the file with the file-plugin via the readAs…() commands, but had no luck so far.

Can anyone give me a hint how to open an external file? Thanks!


#9

Thx for sharing,

as of new native coding convention, you need to add file to the constructor and then use code like below. Next, the externalRootDirectory is android only, so I replaced with dataDirectory.

Got this working on Android. Won’t work on Ionic View Pro (file plugin not supported).

Next adventure for me: find the file and put it in a socialshare (or email composer).

saveFile(body) {
    let fileName = "team.csv"
    this.file.writeFile(this.file.dataDirectory, fileName, body, true)
      .then(
      _ => {
        alert('Success ;-)'+this.file.dataDirectory)
      }
      )
      .catch(
      err => {

        this.file.writeExistingFile(this.file.dataDirectory, fileName, body)
          .then(
          _ => {
            alert('Success ;-)2'+this.file.dataDirectory)
          }
          )
          .catch(
          err => {
            alert(err+'Failure'+this.file.dataDirectory)
          }
          )
      }
      )
  }

Regards

Tom


#10

Hey there! Did you manage to put it on social sharing plugin?


#11
this.file.writeFile(this.file.dataDirectory, 'export.csv', text, { replace: true })
      .then((stuff) => {
        if (stuff != null) {
          this.socialshare.share('CSV file export', 'CSV export', stuff['nativeURL'], '');
        } else return Promise.reject('write file')
      })

#12

Did you try to email it? I can see it shared only Subject and Title for me. No file in attachments.

Also do you convert txt to blob or smth before writing it to file?


#13

hi

text is of type string, so no blobbing.

Not sure what goes wrong in your code

and frankly, it has been a while since I used it

But what I remember is that it worked

Sorry

Tom


#14

Was freaking out until i undestood that the ‘filename’ shouldn’t contain any spaces to share correctly. Thanks for your help!