How to create and save CSV files in React Native?
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
Some other way
createFile = () => {
csvString = `${HEADER}`;
RNFetchBlob.fs
.writeFile(FILE_PATH, csvString, "utf8")
.then(() => {
alert("File created succesfully");
this.saveData(JSON.stringify([]));
this.setState({
users: []
});
})
.catch(error => console.error(error));
};
writeCSV = () => {
try {
let rowData = [{
Name: "ABC",
MobileNo: 9999999999,
Age: 23
}, {
Name: "DEF",
MobileNo: 9999999998,
Age: 24
}]
const csvString = `${HEADER}${this.ConvertToCSV(rowData)}`;
RNFetchBlob.fs
.writeFile(FILE_PATH, csvString, "utf8")
.then(() => {
alert("File updated succesfully");
})
.catch(error => alert(error));
} catch (error) {
// Error retrieving data
}
};
ConvertToCSV = objArray => {
var array = typeof objArray != "object" ? JSON.parse(objArray) : objArray;
var str = "";
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;
};