i use react-native-fs & xlsx in my project.
when open app in web browser (chorom , microsoft Edge , ...) return Cannot read properties of undefined (reading 'RNFSFileTypeRegular') error.
thanks to lead me.
import React from "react";
import { } from "react-native";
import xlsx from 'xlsx';
var RNFS = require('react-native-fs');
export const exportDataToExcel = (fileName, data, headerTitle) => {
let wb = xlsx.utils.book_new();
let ws = xlsx.utils.json_to_sheet(data, { header: [headerTitle] });
xlsx.utils.book_append_sheet(wb, ws, fileName)
const wbout = xslx.write(wb, { type: 'binary', bookType: "xlsx" });
RNFS.writeFile(RNFS.ExternalStorageDirectoryPath + `/${formName}.xlsx`, wbout, 'ascii').then((r) => { console.log(`create xlsx is success`) })
.catch((e) => { console.error(`create xlsx is failed`) });
}
best answer found :
import { Component } from "react";
import * as XLSX from "xlsx";
import * as FileSaver from "file-saver";
export function exportDataToExcel(fileName, headerTitle, data) {
try {
const fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset = UTF-8";
const fileExtension = ".xlsx";
var ws = XLSX.utils.json_to_sheet(data);
var wb = { Sheets: { data: ws }, SheetNames: ["data"] };
var excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
var excelData = new Blob([excelBuffer], { type: fileType });
FileSaver.saveAs(excelData, fileName + fileExtension);
}
catch (error) {
console.error(`get error ${error} in ExportDataToExcel exportDataToExcel`);
}
}