Read Excel data and visualize with React

Read Excel data and visualize with React

Hello everyone, I will tell you Excel data read and fetched data visualization in this article. We will use xlsx and tremor.so libraries and in this article after, you can create interactive components.

First, I will install the requriment packages and create a sample Excel Data.

In addition, we will install React via Vite and write code JSX.

Article content

And, starting "npm install" command also, We installed React via Vite.

Article content

Okay, let's install the xlsx and tremor.so libraries;

  • xlsx; You can read Excel and convert to json objects.
  • tremor; You created objects of json, you can visualize or KPI Metric card via Tremor.

Install xlsx via NPM;

npm install xlsx        

Install tremor.so via NPM;

npm install @tremor/react        

And "tremor" also has package dependency with tailwindcss we will install tailwindcss.

npm install -D tailwindcss postcss autoprefixer 
npx tailwindcss init -p        

Alt last, we finished installing the packages and let's start the project.

npm run dev        

Before, We will create an xlsx file via Excel. For example, We have a company and company sales data on hand in addition this data want analysis and visualization.

  • And, We will create KPI metric cards' and inside add month change percentange.
  • In addition, We will do trend and visualization with company's sales.

I have sample data on Excel;

Article content

Now, We can read Excel data and convert json object. First, We can import libraries dependency. In addition We will usecustom hooks.

import { useEffect, useState } from "react";
import * as XLSX from "xlsx";        

And, create file for custom hooks, custom hook will run below code.

const useFile = () => {
  // Returned Excel JSON datas keep.
  const [data, setData] = useState([]);

  useEffect(() => {
    // Fetch Excel file.
    fetch("./datas.xlsx")
      // Convert to ArrayBuffer.
      .then((res) => res.arrayBuffer())
      .then((data) => {
        const wb = XLSX.read(data, { type: "buffer" });

        const wsname = wb.SheetNames[0];
        const ws = wb.Sheets[wsname];

        // Convert to JSON.
        const json = XLSX.utils.sheet_to_json(ws);

        setData(json);
      });
  }, []);

  return data;
};        

Now let's check the returned JSON data. We have done this and output the result to the console.

Article content

When I checked the output, we saw the image we wanted, but we should make some changes and the "tremor" library needs a data format.

Article content

Now we will change the object shown this in the picture. We will create a new component.

const useConverted = (value) => {
  const result = {};

  value.forEach(({ Month, Product, Amount, TotalPrice }) => {
    if (!result[Product]) {
      result[Product] = { fyAmount: 0, trend: {} };
    }

    if (!result[Product].trend[Month]) {
      result[Product].trend[Month] = { amount: 0, totalPrice: 0 };
    }

    result[Product].fyAmount += Amount;
    result[Product].trend[Month]["amount"] += Amount;
    result[Product].trend[Month]["totalPrice"] += TotalPrice;
  });

  const final = Object.keys(result).map((key) => {
    return { product: key, ...result[key] };
  });

  return final;
};        

We created a new component and gave it component a custom hook. Finally, we completed the code output.

Article content

We have completed the sales data. And we begin the data visualization stage. First, we will choose which line chart component to use. In addition, we will trend analysis, and can line chart.

<section className="p-10 flex justify-center items-center h-screen gap-3">
        {data.map((item) => {
          const trend = Object.keys(item.trend).map((key) => {
            return {
              date: key,
              ...item.trend[key],
            };
          });

          return (
            <Card key={crypto.randomUUID()}>
              <Title>{item.product} Product Sales Trend</Title>
              <LineChart
                className="mt-6"
                data={trend}
                index="date"
                categories={["totalPrice"]}
                colors={["emerald", "gray"]}
                yAxisWidth={40}
                curveType="monotone"
              />
            </Card>
          );
        })}
</section>        

Finally, We created chart components at bellow.

Article content

As a result, if we have an Excel data and we want to visualize the output; using xlsx and tremor.so libraries. When the data format is selected you only need to convert the data format that the libraries support.

To view or add a comment, sign in

More articles by Enes Akkaya

  • Derin Öğrenme DeepFace Uygulaması

    Merhaba, ML Öğrenmesinin alt dalı olan Derin Öğrenmeye giriş yapabileceğimiz yüz tanıma ile ilgili bir yazı hazırlamak…

  • Python ile Web Tabanlı Veri Görselleştirme

    Merhaba, bu yazı içerisinde Python ile interaktif şekilde kullanabileceğiniz ve Web tabanlı verilerinizi analiz…

  • React Todo Project with JSON Server

    Hello everyone, In this article will create a todo project via React and JSON Server. We will development REST API with…

  • Streamlit Uygulama Geliştirme

    Merhaba, bu yazı içerisinde Streamlit ile proje geliştirmeyi, prototip hazırlama ve dinamik yapılar nasıl…

  • JavaScript ile Veri Analizi

    Merhaba, Python üzerinde Pandas kütüphanesi kullanarak; veri analizi, veri manipülasyonu gibi yapılar oluşturabiliyoruz…

  • React useState's usage

    Hello everyvone, I will tell you useState hook's using on the React. React creates user interface design so, a lot of…

    1 Comment
  • Typescript Değişkenler

    Merhaba, bu yazı içerisinde JavaScript'in bir üst kümesi olarak diyebileceğimiz TypeScript üzerinde değişken…

  • React Web Scraping

    Merhaba, bu yazı içerisinde genel olarak birden fazla yazılım dilleri üzerinde kullanan "Web Scraping" olarak geçen ve…

  • React Context API

    Merhaba, bu yazı içerisinde Context API konusu hakkında başlangıç ve bilgilendirici nitelikte bir yazı hazırlamaya…

  • React useReducer

    Merhaba bu yazı içersinde React içerisinde daha önceden yazı olarak oluşturduğum; useState yapısının alternatifi olarak…

Others also viewed

Explore content categories