有没有一种方法可以在React native中从js代码创建Excel文件?您可以共享该库,包括示例如何使用它吗?
我需要导出一些数据并将其下载到excel文件中,然后将其下载到手机中。
谢谢!
答案 0 :(得分:3)
如果使用Expo,以下代码将为您工作。它会创建一个工作表,然后为用户创建一个共享对话框以在用户喜欢的任何应用程序(例如电子邮件,Office等)中打开它:
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'
});
答案 1 :(得分:1)
您可以将JSON转换为Excel文件
您必须使用两个pacakge
这是一个示例
如果要编写Excel文件
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)=>{/* :( */});
如果要阅读Excel文件
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")
答案 2 :(得分:0)
我会使用JSON,它是JavaScript固有的,可以为imported directly into Excel
如果您还不知道如何做,那么这是一篇说明如何从JS对象创建JSON文件的文章: