gpt4 book ai didi

javascript - 如何在 React Native 中创建和保存 CSV 文件?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:01:56 26 4
gpt4 key购买 nike

我的 React Native 应用程序(仅适用于 Android)是一个基本应用程序,它会在用户开始录制视频时收集一些传感器数据。我有三个传感器数据阵列:加速度计、陀螺仪和光。我想将它们作为 .csv 文件保存到设备中,以便我可以在后续步骤中使用它们。目前,我可以将它们保存在 .txt 中(使用 react-native-fs,但它们不支持 .csv 扩展名)但我想要的是 .csv 。在 React Native 中有什么方法可以做到这一点吗?

数据看起来像这样:

this.accelerometer = [
{x: 12, y: 15, z: 17},
{x: 12, y: 15, z: 17},
...
{x: 12, y: 15, z: 17},
]

this.gyroscope = [
{x: 12, y: 15, z: 17},
{x: 12, y: 15, z: 17},
...
{x: 12, y: 15, z: 17},
]

this.light = [6, 7, 8, 9, 10,.., 11]

所需的.csv,例如accelerometer.csv:

x ,y ,z
12,15,17

最佳答案

您可以使用 react-native-fetch-blob写入设备的文件系统。 (我也想知道这个!)

我们首先将值数组转换为字符串。如果我们的值由 , 逗号分隔并且我们的行由 \n 换行符分隔,那么我们的字符串是 csv。我们可以获取该字符串,将其写入具有 .csv 文件扩展名的文件,我们就有了一个 .csv 文件。

这是执行此操作的代码:

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

这种方法适用于我的 Android 7.x 测试设备。

如果有帮助,我还会分享 link to the equivalent code在我的 react-native 项目中

关于javascript - 如何在 React Native 中创建和保存 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45660768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com