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

Browser freezes unexpectedly every 10-15 minutes

I have an application that displays 10 charts using dygraphs to monitor data. The charts are updated by sending ajax requests to 4 different servlets every 5 seconds. However, after approximately 10-15 minutes, my browser crashes with the "aw! snap" messag ...

Calculating the total of selected values in Checkboxes and Selectors using KnockoutJS

I have already created this using jQuery. You can view it on JSFiddle: JSFiddle HTML: <div class="container"> <header> <h3>The Crazy Things We'll Do for Money</h3> <div class="small"><em>An ele ...

Guidelines for cycling through a series of HTTP requests and effectively saving the data from each cycle into an array

Utilizing Spotify's API search feature, I am working with an array of SongSearchParams that consist of title and artist parameters: export class SongSearchParams { public title: string; public artist: string; constructor(title: string, a ...

Processing JSON data with an extensive number of columns using Spark

Currently, I am working on a Proof of Concept for a Spark application written in Scala running in LOCAL mode. Our task involves processing a JSON dataset with an extensive 300 columns, though only a limited number of records. Utilizing Spark SQL has been s ...

Exploring the integration of JSON data requests into a SQLite database using Angular2 and Ionic2

I am currently facing an issue with inserting JSON format data from a request into a SQLite database within my app. Even though the database and table are set up properly, I am having trouble getting the INSERT function to work correctly. Below is the sn ...

When implementing v-model on a v-dialog component, it causes the element within an array to

There is an array of apps with links, and a Dialog component that has v-model="dialog" to close it. However, after adding v-model to the v-dialog, the functionality of the apps is affected. The current app is passed as a prop to Dialog, but it always sends ...

A guide on resetting a Nodemon server using code

At the beginning of server start, I have an array of JSON objects that are updated. But if I make changes to the JSON data using NodeJS FS instead of manually editing it, Nodemon does not restart. Is there a way to programmatically restart nodemon? ...

What is the reason for sending a JSON string in an HTTP POST request instead of a JavaScript object in AngularJS

When sending data via a post request in AngularJS, the code may look like this: $http({ method: 'POST', url: url, data: inputParams, headers: headers }) .then(function succes(response) { successCallBack(response.data); } Here is h ...

Gulp and Vinyl-fs not functioning properly when trying to save in the same folder as the source file due to issues with

After exploring a variety of solutions, I have yet to find success in modifying a file in place using Gulp.js with a globbing pattern. The specific issue I am facing can be found here. This is the code snippet I am currently working with: var fstrm = re ...

Navigate through the options on the left menu by sliding your

I'm attempting to create a menu that slides in a submenu from the left on hover, but the issue is that with this code, all submenus open instead of just the one related to the hovered link. Here is my HTML code: <ul id="NavMenu"> ...

Guide to updating information in Firestore using Node.js, embedded in a map array

Encountered an issue with the following error message: Error: Unable to access 'set' property of undefined. I am attempting to update the endTime field in my script for each user, calculate total hours worked, and then update the 'totalTi ...

Is the required attribute for form submission in Material UI not verifying in another file?

It seems that I may be importing incorrectly because a required field does not display a "please fill in this field" popover when attempting to submit a form. The imported classes are as follows: import * as React from 'react' import FormContro ...

Encountered an error while trying to access an undefined property during an Angular Karma

I'm currently working on testing a service function that involves multiple $http.get() calls. The function being tested returns a promise but the test is failing with an error stating response is undefined. Below is the test script: it('should ...

The $firebaseObject variable is not defined

My AngularJs + AngularFire setup includes email/password authentication and a node called "users" to list authenticated users. Here is a snapshot: Within my authentication service, I have an AngularJs factory: .factory('Auth', function($firebas ...

Is it possible to decode nested JSON into a flat structure?

Is it possible in Go to unmarshal nested json into a differently structured struct, such as flattening out the nesting? { "id":1, "person":{ "name": "Jack" "extra": { "age": 21 } } } type Item struct { ID int64 `json:"id"` ...

DataTables' JsSON output converts individual elements into arrays

I am currently working on developing an API endpoint that is intended to return a single element based on its id. However, I am facing an issue where the JsonResult method converts the data from my DataTable into an array even though it should only contain ...

Steps for moving data from a JavaScript variable to a Python file within a Django project

I have created a unique recipe generator website that displays each ingredient as an image within a div. When the div is clicked, it changes color. My goal is to compile the ids of all selected divs into one array when the submit button is clicked. I have ...

Position object in the middle using jQuery and CSS

Trying to center an absolutely positioned object horizontally using CSS and jQuery is proving to be a challenge. The use of jQuery is necessary due to the varying widths of the objects. Hover over the icons in my jsFiddle to see the issue. Check out the j ...

Using JQuery Slider to call a function without the need for an ID, instead utilizing the object directly

Currently, I am working on implementing a Slider using JQuery, and I have encountered an issue in my code. The function is set to run when the page loads, creating a slider with the Id specified in the div element: $(function() { $( "#slider& ...

Conceal the <p> element when the user interacts with the internal href

After creating this document using JQuery, whenever the user clicks on different internal links, a div with id = "change" is loaded which effectively "erases" the content. My challenge at the moment is that while images are successfully deleted, text rema ...