is there a way to create an excel file from js code in React native? Can you share the library, including the examples how to use it?
I need to export and download some data to excel file and download it to mobile phone.
Thank you!
is there a way to create an excel file from js code in React native? Can you share the library, including the examples how to use it?
I need to export and download some data to excel file and download it to mobile phone.
Thank you!
If using Expo, the following code should work for you. It creates a Sheet and then creates a Share dialog for the user to open it in which ever app they like like Email, Office, etc:
import XLSX from 'xlsx';
import * as FileSystem from 'expo-file-system';
import * as Sharing from 'expo-sharing';
var data = [{
"name": "John",
"city": "Seattle"
},
{
"name": "Mike",
"city": "Los Angeles"
},
{
"name": "Zach",
"city": "New York"
}
];
var ws = XLSX.utils.json_to_sheet(data);
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Cities");
const wbout = XLSX.write(wb, {
type: 'base64',
bookType: "xlsx"
});
const uri = FileSystem.cacheDirectory + 'cities.xlsx';
console.log(`Writing to ${JSON.stringify(uri)} with text: ${wbout}`);
await FileSystem.writeAsStringAsync(uri, wbout, {
encoding: FileSystem.EncodingType.Base64
});
await Sharing.shareAsync(uri, {
mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
dialogTitle: 'MyWater data',
UTI: 'com.microsoft.excel.xlsx'
});
You can convert JSON to excel file
You have to use two pacakge
here is an example
if you want to write Excel file
import { writeFile, readFile } from 'react-native-fs';
import XLSX from 'xlsx';
var data = [
{"name":"John", "city": "Seattle"},
{"name":"Mike", "city": "Los Angeles"},
{"name":"Zach", "city": "New York"}
];
var ws = XLSX.utils.json_to_sheet(data);
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb,ws,"Prova");
const wbout = XLSX.write(wb, {type:'binary', bookType:"xlsx"});
var RNFS = require('react-native-fs');
var file = RNFS.ExternalStorageDirectoryPath + '/test.xlsx';
writeFile(file, wbout, 'ascii').then((r)=>{/* :) */}).catch((e)=>{/* :( */});
if you want to read Excel file
import { writeFile, readFile } from 'react-native-fs';
import XLSX from 'xlsx';
const filePath="/Users/copoo/Downloads/Data.xlsx";
const excelFile=await RNFS.readFile(filePath,'ascii');
const workbook = XLSX.read(excelFile, {type:'binary'});
console.log(workbook,"excelFile")
0.16.0 and the code provided can read the file fine.I would use JSON, which is native to JavaScript, and can be imported directly into Excel
If you don't already know how, Here is a post explaining how to create a JSON file from a JS object: