Open In App

How To Represent Excel Data as Pie Chart in ReactJS?

Last Updated : 21 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In today's data-driven world, visualizing information is crucial for understanding trends and making informed decisions. Pie charts are a powerful tool for displaying the proportions of a whole, making them ideal for presenting Excel data in a clear and intuitive manner within a ReactJS application. This article provides an explanation on how to seamlessly transform Excel data into dynamic pie charts using ReactJS and Chart.js.

Prerequisites:

Approach to represent Excel data in the form of Piechart

  • Begin by creating a React functional component to handle file uploads and chart rendering.
  • Utilize libraries such as xlsx for parsing Excel files and react-chartjs-2 for integrating Chart.js into React.
  • Implement an <input type="file" /> element to enable users to upload Excel files directly.
  • Utilize FileReader to read uploaded files and xlsx library to parse Excel data into JSON format.
  • Extract relevant data (labels and values) from the parsed Excel data.
  • Structure the data into Chart.js format, including datasets and labels required for pie chart visualization.
  • Customize chart appearance and behavior using Chart.js options such as colors, tooltips, and legends.
  • Render the pie chart dynamically within the React component, ensuring responsiveness and maintainability.
  • Explore Chart.js plugins like chartjs-plugin-datalabels to add data labels inside pie slices for enhanced readability.
  • Fine-tune plugin settings to match specific visualization requirements and improve user interaction.

Steps to implement piechart in react based on the excel data

Step 1: Create a react project app using following command.

npx create-react-app <-Project-Name->

Step 2: Navigate to the Project Directory by below command.

cd <-Project-Name->

Project Structure:

Screenshot-2024-06-13-184259
Project Structure

Step 3: Now, Install some dependencies that work with excel and piechart.

npm install chart.js chartjs-plugin-datalabels react-chartjs-2 xlsx

Updated dependencies

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"chart.js": "^4.4.3",
"chartjs-plugin-datalabels": "^2.2.0",
"react": "^18.3.1",
"react-chartjs-2": "^5.2.0",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
"xlsx": "^0.18.5"
},

Step 4: Create ExcelToCharts.js file in components folder, and update the below code in that file.

JavaScript
import React, { useState } from 'react';
import * as XLSX from 'xlsx';
import { Pie } from 'react-chartjs-2';
import { Chart, ArcElement, Tooltip, Legend } from 'chart.js';
import ChartDataLabels from 'chartjs-plugin-datalabels';

// Register Chart.js components and plugins
Chart.register(ArcElement, Tooltip, Legend, ChartDataLabels);

const ExcelToCharts = () => {
  const [chartData, setChartData] = useState(null);
  const [key, setKey] = useState(0);

  const handleFileUpload = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();

    reader.onload = (e) => {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: 'array' });
      const sheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[sheetName];
      const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

      processExcelData(jsonData);
    };

    reader.readAsArrayBuffer(file);
  };

  const processExcelData = (data) => {
    // Extract labels and values
    const labels = [];
    const values = [];

    for (let i = 1; i < data.length; i++) {
      labels.push(data[i][0]);
      values.push(data[i][1]);
    }

    setChartData({
      labels: labels,
      datasets: [
        {
          label: 'Data',
          data: values,
          backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)',
          ],
          borderColor: [
            'rgba(255, 99, 132, 1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)',
          ],
          borderWidth: 1,
        },
      ],
    });

    setKey((prevKey) => prevKey + 1); // Force re-render of chart
  };

  const pieOptions = {
    maintainAspectRatio: false,
    responsive: true,
    plugins: {
      legend: {
        position: 'top',
      },
      tooltip: {
        enabled: true,
      },
      datalabels: {
        formatter: (value, context) => {
          return value;
        },
        color: 'black',
        font: {
          weight: 'bold',
        },
      },
    },
  };

  return (
    <div>
      <h1>Excel to Pie Chart</h1>
      <input type="file" accept=".xlsx, .xls" onChange={handleFileUpload} />
      {chartData && (
        <div style={{ width: '300px', height: '300px', margin: 'auto' }}>
          <Pie key={key} data={chartData} options={pieOptions} />
        </div>
      )}
    </div>
  );
};

export default ExcelToCharts;


Step 5: Now import ExcelToCharts.js component in App.js and some styling in App.css.

CSS
// App.css

.App {
  text-align: center;
  padding: 20px;
}

input {
  margin: 20px;
}

h1, h2 {
  color: #333;
}
JavaScript
// App.js
import React from 'react';
import ExcelToCharts from './components/ExcelToCharts';
import './App.css';

const App = () => {
  return (
    <div className="App">
      <ExcelToCharts />
    </div>
  );
};

export default App;

Format of the data in Excel to make piechart

Screenshot-2024-06-13-185558
Excel Format


Step 6: Run the react application using following command.

npm run  start

Output

Screenshot-2024-06-13-185735
output with piechart of excel data

In this way, we can create piechart of any excel data, and even we can create multiple piechart if we have multiple columns in the excel sheet.


Next Article

Similar Reads