What is the process for extracting images from an Excel file and converting them into JSON format?

I have a spreadsheet file with columns labeled as image and name. My goal is to extract the image, convert it to ByteArray, and save the data as a JSON object structured like this:

{ image: ByteArrya, name: string }
.

Here is the JavaScript form code I am working with:

<label className="flex items-center gap-3 px-3 py-2 bg-[#1D6F42] text-white text-blue rounded-md cursor-pointer">
    <RiFileExcel2Line size={22} />
    <span className="text-base leading-normal">Upload From Excel</span>
    <input type="file" className="hidden" disabled={formLoading} onChange={(e) => handleFormSubmit("file", e)} accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
</label>

I am looking for a JavaScript function that can take an xlsx file input and then convert it into JSON data.

Answer №1

To read an xlsx file using SheetJS and load image data from a URL into Base64 String, the following code can be used:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>XLSX Frontend Reading</title>
    <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
</head>
<body>
<input type="file" id="xlsxFileInput"/>
<script>
    const fileInput = document.getElementById('xlsxFileInput');

    fileInput.addEventListener('change', (e) => {
        const file = e.target.files[0];

        // use FileReader to read xlsx file
        const reader = new FileReader();
        reader.onload = function (e) {
            const data = new Uint8Array(e.target.result);

            const workbook = XLSX.read(data, {type: 'array'});

            const worksheet = workbook.Sheets[workbook.SheetNames[0]];

            const jsonData = XLSX.utils.sheet_to_json(worksheet, {header: 1});

            const headerRow = jsonData[0];
            let imageIndex = -1;
            let nameIndex = -1;
            // Find the image index and name index
            for (let i = 0; i < headerRow.length; i++) {
                if (headerRow[i] === "image") {
                    imageIndex = i;
                }
                if (headerRow[i] === "name") {
                    nameIndex = i;
                }
                if (imageIndex >= 0 && nameIndex >= 0) {
                    break;
                }

            }

            console.log(imageIndex);
            console.log(nameIndex);

            let result = [];
            for (let i = 1; i < jsonData.length; i++) {
                const row = jsonData[i];
                const resultJsonData = {};
                for (let j = 0; j < row.length; j++) {
                    const cellValue = row[j];

                    if (j === imageIndex) {
                        console.log(cellValue);
                        //
                        const img = new Image();

                        // Set the src attribute of the Image object to the URL of the image, it may be a read URL on your operating machine
                        img.src = cellValue;

                        img.onload = function () {
                            const canvas = document.createElement('canvas');
                            const ctx = canvas.getContext('2d');
                            canvas.width = img.width;
                            canvas.height = img.height;
                            ctx.drawImage(img, 0, 0);
                            // Transfer the image to base64
                            const base64String = canvas.toDataURL('image/jpeg');

                            resultJsonData.image = base64String;

                            console.log(base64String);
                        };
                    }


                    if (j === nameIndex) {
                        resultJsonData.name = cellValue;
                    }
                }
                result.push(resultJsonData);
            }
            console.log(result);

        };

    });
</script>

</body>
</html>

Answer №2

Reading images from an xlsx file is not as straightforward as reading string values. An XLSX file actually consists of a zipped archive containing multiple XML files. One effective solution could involve utilizing a ZIP library to extract the necessary information, such as the image's anchor location (similar to how LibreOffice allows you to anchor images when opening an xlsx file). By parsing this anchor value, you can determine the corresponding row and column for the image.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Applying reduce method for accessing object information within an array and transforming its structure

In my data structure, I have a list of deliveries that includes different cities and the number of units delivered to each city: var deliveries = [{ location: "Chicago", units: 10 }, { location: "San Francisco", units: 5 }, { location: ...

Issue with Backbone: Unable to access property 'fn' as it is undefined

When I attempt to run the code below, I encounter an error that says "Cannot read property 'fn' of undefined" due to jquery not being found. requirejs.config({ baseUrl: "/static/javascript", paths: { jquery: "vendor/jquery", undersco ...

jQuery compatible JavaScript plugin

Currently, I am in the process of developing a JavaScript plugin. My goal is for it to make use of jQuery functionalities, while also gracefully degrading if jQuery is not present on the page. For instance, jQuery users would initiate a slideshow by calli ...

Having trouble with VueJS method not getting called after an asynchronous function callback?

I'm currently utilizing VueJS along with Stripe to create a form that can be submitted without needing to refresh the page. While the Stripe functionality is operational, the issue I'm facing doesn't seem to be directly related to Stripe. T ...

*ngFor is not rendering the array data and no error is being shown

Currently utilizing mongoDB's $filter aggregation feature, which has successfully generated the expected output from my query. However, I am encountering an issue with my HTML code as *ngFor is not displaying the data and no errors are being shown in ...

When working with DNN, I attempted to redirect using JavaScript code, but found that I continue to see the same page after the form submission code

Here is the code I am using to submit a form. When the button is clicked, it will trigger the Checkout() function. function postURL(url) { var form = $('<form action="' + url + '" method="post">' + "<input type=& ...

I am looking to showcase a series of icons linked together by connecting lines

I have successfully designed the layout and added icons, but I am facing difficulty in creating connecting lines between them. I attempted to utilize CSS borders and pseudo-elements, yet I cannot achieve the desired outcome. If anyone could offer a CSS-ba ...

Tips for establishing a connection with an MQTT mosquito broker in a React application

I am currently working on establishing a connection between my React web application and a mosquito broker that is hosted on Docker. I have decided to utilize the MQTT.js library for this purpose, which you can find here. Below is the code snippet that I ...

Creating an interactive amchart that is connected to a database - a step-by-step guide

I am looking to create a dynamic chart that will display call answers and attempts. The database will be updated every 1 minute, causing the chart to also update in real-time. I would like to use Amchart for this visualization, however, I am unsure of how ...

Unresponsive JavaScript on specific element IDs

I'm experimenting with making three lines perform different animations: line 1 rotating 45deg and translating, line 2 becoming opaque, and line 3 rotating -45deg and translating. Check out my JS Fiddle here <a href="#"><div id="menu" onclic ...

Can a href from a "<Link>" component be passed through a Higher Order Component (HOC) into an "<a>" tag?

I am currently facing a situation with the main component where I have the following code: <Link href={'test'}> <PrimaryAnchor>Welcome</PrimaryAnchor> </Link> Within the PrimaryAnchor component, the code looks like ...

To ensure responsiveness in JavaScript, adjust the width to 100%

Recently, I came across this piece of code: <div style="text-align:center; max-width:500px; width:100%; margin:auto"> <script type="text/javascript" src="transition_example.js"></script></div> Here is the content of transition ...

JavaScript click event to open a URL in a new window

I am trying to create a hyperlink with text using HTML, and I want it so that when the user clicks on it, it redirects to a specific URL. I am new to JavaScript! Here is my code: <a class="dt-button add_new_table_entry DTTT_button DTTT_button_new" tab ...

Configuring Protractor to customize Safari settings such as adjusting window size

Is there a way to specify the window size in Safari similar to how we set args and prefs in chromeOptions? I attempted the following setup using Protractor 4.5.1 and Safari 12.0 on Mac: safari: { name: 'Safari', browserName: 'safar ...

Combining React with the power of Express

Currently experimenting with React+Express and encountering an issue related to routing express: router.get('/testCall', function(req, res) { res.json([{id: 'test'}]); }) react: fetch('/testCall') .then((re ...

Converting a JSON array stored in a local file to a TypeScript array within an Angular 5 project

I'm currently working on developing a web app using Angular 5. My JSON file has the following structure: [ { "id": 0, "title": "Some title" }, { "id": 1, "title": "Some title" }, ... ] The JSON file is store ...

javascript code to fetch the full Date object using user input for both date and time

Two input fields are available: <input type="date" ng-model="year"> <input type="time" ng-model="time"> The goal is to combine these values into a Date object. For example: new Date(year, time); Any suggestions on how to achieve this? ...

Ensuring security against cross site scripting attacks on window.location.href

Currently, I'm utilizing window.location.href to redirect the page to an external URL: <Route exact path={rootUrl} component={() => { window.location.href =`https://${window.location.hostname}/www/testurl?google=true`; return null; }} /> How ...

Vue paired with Rainyday.js

I attempted to incorporate Vue with rainyday.js by following different resources, but unfortunately could not find any relevant information. Can anyone provide guidance on how to successfully implement rainyday.js with Vue? <body onload="run();"> ...

Issue with Vue.js v-for not displaying component

Hello, I am facing an issue with the v-for feature as it is not rendering at all. You can view the fiddle by clicking on this link https://jsfiddle.net/tadeyemi/k6s4gv85/. I am puzzled as to why it's not working. Can anyone provide some insight? < ...