Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and save CSV files in React Native?

My React Native app (on android only) is a basic app that will collect some sensors data when users start recording video. I have three arrays of sensors data: accelerometer, gyroscope, and light. I want to save them to the device as .csv files so I can use them for the next steps. Currently, I can save them in .txt (using react-native-fs, but they do not support .csv extension) but what I want is .csv. Is there any way to do that in React Native?

Data will look like this:

this.accelerometer = [
  {x: 12, y: 15, z: 17},
  {x: 12, y: 15, z: 17},
  ...
  {x: 12, y: 15, z: 17},
]

this.gyroscope = [
  {x: 12, y: 15, z: 17},
  {x: 12, y: 15, z: 17},
  ...
  {x: 12, y: 15, z: 17},
]

this.light = [6, 7, 8, 9, 10,.., 11]

Desired .csv, for example accelerometer.csv:

x ,y ,z
12,15,17
like image 499
Huy Vo Avatar asked Aug 13 '17 13:08

Huy Vo


People also ask

How do I export a csv file?

Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited). Note: The different formats support different feature sets.


1 Answers

You can use react-native-fetch-blob to write to the device's file system. (I was wondering this too!)

We start by converting an array of values to a string. If our values are separated by , commas and our rows are separated by \n newlines, then our string is csv. We can take that string, write it to a file with a .csv file extension, and voila we have a .csv file.

here's code that does just this:

import RNFetchBlob from 'react-native-fetch-blob';

const values = [
  ['build', '2017-11-05T05:40:35.515Z'],
  ['deploy', '2017-11-05T05:42:04.810Z']
];

// construct csvString
const headerString = 'event,timestamp\n';
const rowString = values.map(d => `${d[0]},${d[1]}\n`).join('');
const csvString = `${headerString}${rowString}`;

// write the current list of answers to a local csv file
const pathToWrite = `${RNFetchBlob.fs.dirs.DownloadDir}/data.csv`;
console.log('pathToWrite', pathToWrite);
// pathToWrite /storage/emulated/0/Download/data.csv
RNFetchBlob.fs
  .writeFile(pathToWrite, csvString, 'utf8')
  .then(() => {
    console.log(`wrote file ${pathToWrite}`);
    // wrote file /storage/emulated/0/Download/data.csv
  })
  .catch(error => console.error(error));

this approach worked for me on an Android 7.x test device.

in case it's helpful, I'll also share a link to the equivalent code inside my react-native project

like image 97
Micah Stubbs Avatar answered Sep 23 '22 19:09

Micah Stubbs