Export Data to Excel with React Native

Learn how to export JSON data from your React Native application to Excel using react-native-fs and xlsx.

Requirements

react-native-fs is a library that provides native filesystem access for React Native. It allows you to read and write files, create directories, copy and move files, download files, and more

xlsx is a library that parses and writes spreadsheet data in various formats, such as XLSX, XLS, CSV, and JSON. It supports creating and modifying worksheets, cells, styles, formulas, and more.

The final code for this example can be found here.

Steps

  1. Create a new react-native project
  2. Install dependencies ( react-native-fs & xlsx )
  3. Setup storage permission
  4. Implement Export Functionality
  5. Final Run & Output

Step 1: Create a new react-native project

Run the following commands :

>> npx react-native init SampleReactNative>> cd SampleReactNative

After running these commands new project being created. Detailed article on step-by-step-guide-to-kick-off-your-first-react-native-project

Step 2: Install dependencies ( react-native-fs & xlsx )

#1: Install and link react-native-fs

>> npm install react-native-fs --save>> react-native link react-native-fs

#2: Install xlsx

>> npm i xlsx --save

Step 3: Setup storage permission ( WRITE_EXTERNAL_STORAGE )

Add the following line in android/app/src/main/AndroidMainfest.xml

<uses-permission android:name="android.permission.INTERNET" />...<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />...

Step 4: Implement Export Functionality

#1.Import react-native-fs and xlsx

var RNFS = require(‘react-native-fs’);import XLSX from ‘xlsx’

#2. Create exportDataToExcel function

  // function to handle exporting
  const exportDataToExcel = () => {

    // Created Sample data
    let sample_data_to_export = [{id: '1', name: 'First User'},{ id: '2', name: 'Second User'}];

    let wb = XLSX.utils.book_new();
    let ws = XLSX.utils.json_to_sheet(sample_data_to_export)    
    XLSX.utils.book_append_sheet(wb,ws,"Users")
    const wbout = XLSX.write(wb, {type:'binary', bookType:"xlsx"});

    // Write generated excel to Storage
    RNFS.writeFile(RNFS.ExternalStorageDirectoryPath + '/my_exported_file.xlsx', wbout, 'ascii').then((r)=>{
     console.log('Success');
    }).catch((e)=>{
      console.log('Error', e);
    });

  }

#3. Final App.js

import React from 'react';
import {View, Text, TouchableOpacity, PermissionsAndroid} from 'react-native';
var RNFS = require('react-native-fs');
import XLSX from 'xlsx';

const App: () => React$Node = () => {

  // function to handle exporting
  const exportDataToExcel = () => {

    // Created Sample data
    let sample_data_to_export = [{id: '1', name: 'First User'},{ id: '2', name: 'Second User'}];

    let wb = XLSX.utils.book_new();
    let ws = XLSX.utils.json_to_sheet(sample_data_to_export)    
    XLSX.utils.book_append_sheet(wb,ws,"Users")
    const wbout = XLSX.write(wb, {type:'binary', bookType:"xlsx"});

    // Write generated excel to Storage
    RNFS.writeFile(RNFS.ExternalStorageDirectoryPath + '/my_exported_file.xlsx', wbout, 'ascii').then((r)=>{
     console.log('Success');
    }).catch((e)=>{
      console.log('Error', e);
    });

  }
  const handleClick = async () => {

    try{
      // Check for Permission (check if permission is already given or not)
      let isPermitedExternalStorage = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE);

      if(!isPermitedExternalStorage){

        // Ask for permission
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          {
            title: "Storage permission needed",
            buttonNeutral: "Ask Me Later",
            buttonNegative: "Cancel",
            buttonPositive: "OK"
          }
        );

        
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          // Permission Granted (calling our exportDataToExcel function)
          exportDataToExcel();
          console.log("Permission granted");
        } else {
          // Permission denied
          console.log("Permission denied");
        }
      }else{
         // Already have Permission (calling our exportDataToExcel function)
         exportDataToExcel();
      }
    }catch(e){
      console.log('Error while checking permission');
      console.log(e);
      return
    }
    
  };

  return (
    <View
      style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        flex: 1,
      }}>
      <TouchableOpacity
        onPress={() => handleClick()}
        style={{
          width: '50%',
          paddingVertical: 10,
          paddingHorizontal: 15,
          backgroundColor: 'blue',
          marginVertical: 20,
        }}>
        <Text style={{textAlign: 'center', color: 'white'}}>
          Export to Excel
        </Text>
      </TouchableOpacity>
    </View>
  );
};

export default App;

Step 5: Final Run & Output

>> react-native run-android

The final code for this example can be found here.

No comments:

Post a Comment