React Native:如何从代码创建excel文件? [英] React Native: How to create excel file from code?

查看:29
本文介绍了React Native:如何从代码创建excel文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 React Native 中从 js 代码创建一个 excel 文件?可以分享一下这个库吗,包括如何使用它的例子?

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?

我需要导出和下载一些数据到excel文件并下载到手机.

I need to export and download some data to excel file and download it to mobile phone.

谢谢!

推荐答案

如果使用 Expo,以下代码应该适合您.它创建一个工作表,然后为用户创建一个共享对话框,以在他们喜欢的任何应用程序中打开它,例如电子邮件、Office 等:

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'
});

这篇关于React Native:如何从代码创建excel文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆