The direction to the Excel document for conversion into JSON

I have a project in progress where I'm currently working on converting an Excel sheet to JSON. Once the data is converted, it will be displayed using jQuery Datatables on the browser. My code is functioning as expected, but I am encountering an issue when the Excel file is located in a different folder than the HTML file. How can I retrieve the path to the Excel file from another directory to use in my script?

Below is the snippet of the code:

function loadExcelData(callback) {

        var excelUrl = "LICENCIAMENTOS PROJECTOS.xlsx";
        var request = new XMLHttpRequest();
        request.open("GET", excelUrl, true);
        request.responseType = "arraybuffer";

        request.onload = function(event) {
            var arrayBuffer = request.response;
            /* Convert data to binary string */
            var data = new Uint8Array(arrayBuffer);
            var dataArray = new Array();
            for (var i = 0; i != data.length; ++i) dataArray[i] = String.fromCharCode(data[i]);
            var binaryString = dataArray.join("");

            /* Call XLSX library */
            var workbook = XLSX.read(binaryString, { type: "binary" });

            /* Perform actions with workbook here */

            var sheetIndex = 0; // Change this index to get the desired sheet
            var sheetName = workbook.SheetNames[sheetIndex];

            /* Get worksheet */
            var worksheet = workbook.Sheets[sheetName];

            // Extracting specific range of data from the worksheet
            var extractedData = XLSX.utils.sheet_to_json(worksheet, { range: 4 });
            $("h4").remove();
            callback(extractedData);
        }
        request.send();

    }

    loadExcelData(function(result) {
        console.log(result);
        $("#data-table").show();

        // Initialize DataTable 
        $('#data-table').DataTable({
            "language": {
                "lengthMenu": "Display _MENU_ rows per page",
                "search": "Search:",
                "info":    "Showing _START_ to _END_ of _TOTAL_ entries",
                "next":       "Next",
                "previous":   "Previous"
            },
            "dom": '<"pull-left"f><"pull-right"l>tip',
            "aaData": result,
            "aoColumns": [

            ....

            ]
        });

    });

Answer №1

To specify a relative path for the url, you can input it here.

If your

url = "LICENCIAMENTOS PROJECTOS.xlsx"
, then the path used in oReq.open("GET", url, true); would be
'./LICENCIAMENTOS PROJECTOS.xlsx'
.

In a scenario where your application structure includes spreadsheets within a folder:

index.html
spreadsheets/
   LICENCIAMENTOS PROJECTOS.xlsx

Your url path should be either

spreadsheets/LICENCIAMENTOS PROJECTOS.xlsx
or
./spreadsheets/LICENCIAMENTOS PROJECTOS.xlsx

If you need to navigate back to a folder located elsewhere in an application with this structure:

app/
    index.html
spreadsheets/
   LICENCIAMENTOS PROJECTOS.xlsx

Your url path should be either

../spreadsheets/LICENCIAMENTOS PROJECTOS.xlsx
or
./../spreadsheets/LICENCIAMENTOS PROJECTOS.xlsx

You have the flexibility to backtrack to the location of the spreadsheet as needed.

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

Transforming JSON data into an Angular TypeScript object

Delving into the realm of Angular on my own has been quite an enlightening journey, but I'm currently facing a specific issue: My aim is to create a website using both Spring for the back end and Angular 7 for the front end. However, I've encoun ...

Animating with JQuery utilizing a dynamic attribute

We are facing a challenge with animating multiple divs that share the same class name and have different attribute values: <div class="chart-bar" style="width:10%;" bar-width="100%"></div> <div class="chart-bar" style="width:10%;" bar-wid ...

By default, the HTML table will highlight the specific column based on the current month using either AngularJS or JavaScript upon loading

I am working with a table of 10 products and their monthly sales data. Using Angular JS, I am looking to highlight the entire column based on the current month and year. Additionally, we will also be incorporating future expected sales data into the table. ...

Highlighting table column when input is selected

I am working with a table where each <td> contains an <input>. My goal is to apply the class .highlighted to all the column <td>s when an <input> is being focused on. Additionally, I want to remove this class from all other columns ...

Exploring Nested JSON Data with Pandas

Here is a JSON string that I need to work with: { "2022-09-28T00:45:00.000Z": [ { "value": 0.216, "plantId": "27050937", "man": "pippo" }, ...

What could be causing the misalignment of the Datepicker calendar in Material UI?

I have integrated a datepicker using the library "@mui/x-date-pickers/DatePicker". import { DatePicker } from "@mui/x-date-pickers/DatePicker"; import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment"; import { Locali ...

Issues with loading Datatables table via JSON data in Rails application

I am currently working on a Rails application that is designed to extract data from a JSON file and showcase it in a filterable table. For this purpose, I have decided to utilize datatables.net. However, I have encountered an issue where the table remain ...

Utilize Google Chrome Developer Tools to interact with the "Follow" buttons on the webpage by clicking on them

https://i.stack.imgur.com/W32te.png Here is the script I am currently using: document.querySelectorAll('.components-button components-button-size-mini components-button-type-orange desktop components-button-inline').forEach(btn => btn.click() ...

What is the best way to transfer a PHP string to JavaScript/JQuery for use in a function?

Within my PHP code, I have the following: $welcome = "Welcome!"; echo '<script type="text/javascript">addName();</script>'; Additionally, in my HTML/script portion: <a id="franBTN"></a> <script type="text/javascript ...

Retrieving images linked to a post in WordPress using WP-API

Hey there, I'm currently exploring the WP-API plugin and I've managed to figure out how to retrieve all posts for a custom post type using this URL: http://domain/wp-json/posts?type[]=customType Additionally, I've also discovered how to ge ...

Display a div in JQuery along with all of its associated label elements

Here is my HTML code: <div id="summarySpan" style="padding-left: 20px" hidden> <label id="currentStatusSummary" style="padding-left: 20px" /> <br /> <label id="currentMonitoringSummary" style="padding-left: 20px" /> < ...

Select Menu (Code Languages:CSS, JS, HTML, BBCode)

I'm currently in the process of setting up a BB code for a forum I moderate. Here's the code snippet I'm using to generate a dropdown box that users can add to the signature field of their profiles: <!DOCTYPE html> <html> <d ...

Jquery Ajax failing to retrieve a response

Here's the jQuery script I am using to fetch data from my server: $(".login_button").click(function () { var username = $(".username").val(); var userkey = $(".userkey").val(); $.ajax({ type: "GET", url: "http://192.168.0. ...

Issue with PassportJS and Express 4 failing to properly store cookies/session data

I have a situation with my Express 4 app using Passport 0.3.2. I've set up a passport-local strategy, and it's successfully retrieving the user information when the /session endpoint is provided with a username and password. The issue arises whe ...

Resolving the "Error: Cannot update a React state on an unmounted component" issue

I encountered a console error while attempting to navigate to a new page within my web application. Here's the error message I received: Warning: A React state update was attempted on an unmounted component, which is essentially a no-op. However, t ...

Uncharted Territory: Exploring asynchronous loops with async await and Promise.race?

Currently, I am involved in a project that requires brute forcing a PDF password. To achieve this task, I am using PDF.js to verify the password and implementing promise.race to execute parallel functions for efficient performance. This is how I have str ...

Disable onclick action for programmatically created buttons

I'm facing an issue with the code I'm using to delete messages on my website. The problem is that while newly added messages are being dynamically loaded, the delete button (which links to a message deletion function) does not seem to be working. ...

What is the process for capturing a window screenshot using Node.js?

I am currently conducting research to discover a way to capture a screenshot of a window using Node.js. I have been attempting to achieve this with node-ffi, but I am facing some difficulties at the moment: var ffi = require('ffi'); var user32 ...

In the middleware, the request body is empty, but in the controller, it contains content

Below is my server.js file: import express from "express"; import mongoose from "mongoose"; import productRouter from "./routers/productRouter.js"; import dotenv from "dotenv"; dotenv.config(); const app = expres ...

Refreshing the content in JSON data within PSQL

I am working with a table that holds data in the form of tables stored as JSON in a PostgreSQL column. I am attempting to update a specific cell within this data column, which consists of an array of objects. For example, I need to change the value from " ...