For React Native apps, exporting to Excel or CSV requires different libraries compared to web apps due to the mobile environment's constraints. Here's a comparison and implementation guide:
Compatible Libraries for React Native
-
Excel Export (XLSX/XLS):
- SheetJS (xlsx.js) Community Edition
- Works with polyfills for React Native
- Requires additional setup for filesystem operations
- Bundle size: ~1.5MB (minimizable with tree-shaking)
- react-native-excel-export
- Dedicated React Native wrapper
- Simpler API but less flexible
-
CSV Export:
- No library needed
- Use React Native's filesystem APIs directly
- Lightweight solution (no dependencies)
-
Essential Tools:
- react-native-fs: Filesystem access
- react-native-share: File sharing dialog
Implementation Examples
CSV Export (Recommended for Simplicity)
import RNFS from 'react-native-fs';
import Share from 'react-native-share';
const exportCSV = async (data) => {
// 1. Generate CSV content
const header = Object.keys(data[0]).join(',');
const rows = data.map(obj => Object.values(obj).join(','));
const csv = [header, ...rows].join('\n');
// 2. Save file locally
const path = `${RNFS.DocumentDirectoryPath}/export.csv`;
await RNFS.writeFile(path, csv, 'utf8');
// 3. Share file
await Share.open({ url: `file://${path}`, type: 'text/csv' });
};
Excel Export (Using SheetJS)
import * as XLSX from 'xlsx';
import RNFS from 'react-native-fs';
import Share from 'react-native-share';
// Polyfill needed for React Native
import { Buffer } from 'buffer';
global.Buffer = Buffer;
const exportExcel = async (data) => {
// 1. Create worksheet
const ws = XLSX.utils.json_to_sheet(data);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Data");
// 2. Generate binary
const wbout = XLSX.write(wb, { type: 'base64', bookType: 'xlsx' });
// 3. Save file
const path = `${RNFS.DocumentDirectoryPath}/export.xlsx`;
await RNFS.writeFile(path, wbout, 'base64');
// 4. Share file
await Share.open({ url: `file://${path}`, type: 'application/vnd.ms-excel' });
};
CSV vs Excel in React Native: Key Considerations