Using JavaScript to transform JSON information into Excel format

I have tried various solutions to my problem, but none seem to fit my specific requirement. Let me walk you through what I have attempted.

function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

var CSV = '';    
//Set Report title in first row or line

CSV += ReportTitle + '\r\n\n';

//This condition will generate the Label/Header
if (ShowLabel) {
    var row = "";

    //This loop will extract the label from 1st index of on array
    for (var index in arrData[0]) {

        //Now convert each value to string and comma-seprated
        row += index + ',';
    }

    row = row.slice(0, -1);

    //append Label row with line break
    CSV += row + '\r\n';
}

//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
    var row = "";

    //2nd loop will extract each column and convert it in string comma-seprated
    for (var index in arrData[i]) {
        row += '"' + arrData[i][index] + '",';
    }

    row.slice(0, row.length - 1);

    //add a line break after each row
    CSV += row + '\r\n';
}

if (CSV == '') {        
    alert("Invalid data");
    return;
}   

//Generate a file name
var fileName = "MyReport_";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g,"_");   

//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension    

//this trick will generate a temp <a /> tag
var link = document.createElement("a");    
link.href = uri;

//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";

//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

}

The output I am currently receiving is

CLASSIC_bn_0 CLASSIC_en_0 CLASSIC_en_1 CLASSIC_en_10 CLASSIC_en_11
1             2            28           undefined     undefined 
1             2            28           undefined     undefined 

However, I would like the output to be represented column-wise rather than row-wise as follows:

CLASSIC_bn_0   1   1
CLASSIC_en_0   2   2 
CLASSIC_en_1   28  28
CLASSIC_en_10  28  28
CLASSIC_en_11  undefined undefined          

If anyone has any insights on how to achieve this, I would greatly appreciate your help as I have been stuck on this for quite some time.
Thank you.

Answer №1

Is there a more efficient way to streamline the process by adjusting axes and using array functions instead of messy string concatenation?

var JSONData = [{ "Vehicle": "BMW", "Date": "30, Jul 2013 09:24 AM", "Location": "Hauz Khas, Enclave, New Delhi, Delhi, India", "Speed": 42 }, { "Vehicle": "Honda CBR", "Date": "30, Jul 2013 12:00 AM", "Location": "Military Road,  West Bengal 734013,  India", "Speed": 0 }, { "Vehicle": "Supra", "Date": "30, Jul 2013 07:53 AM", "Location": "Sec-45, St. Angel's School, Gurgaon...</answer1>
<exanswer1><div class="answer accepted" i="58835423" l="4.0" c="1573631274" a="SmFu" ai="5480147">
<p>How about simplifying the process by adjusting axes and utilizing array methods to avoid messy string concatenation?</p>

<p><div>
<div>
<pre class="lang-js"><code>var JSONData = [{ "Vehicle": "BMW", "Date": "30, Jul 2013 09:24 AM", "Location": "Hauz Khas, Enclave, New Delhi, Delhi, India", "Speed": 42 }, { "Vehicle": "Honda CBR", "Date": "30, Jul 2013 12:00 AM", "Location": "Military Road,  West Bengal 734013,  India", "Speed": 0 }, { "Vehicle": "Supra", "Date": "30, Jul 2013 07:53 AM", "Location": "Sec-45, St. Angel's School, Gurgaon, Haryana, India", "Speed": 58 }, { "Vehicle": "Land Cruiser", "Date": "30, Jul 2013 09:35 AM", "Location": "DLF Phase I, Marble Market, Gurgaon, Haryana, India", "Speed": 83 }, { "Vehicle": "Suzuki Swift", "Date": "30, Jul 2013 12:02 AM", "Location": "Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India", "Speed": 0 }, { "Vehicle": "Honda Civic", "Date": "30, Jul 2013 12:00 AM", "Location": "Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India", "Speed": 0 }, { "Vehicle": "Honda Accord", "Date": "30, Jul 2013 11:05 AM", "Location": "DLF Phase IV, Super Mart 1, Gurgaon, Haryana, India", "Speed": 71 }]
JSONToCSVConvertor(JSONData, "Cars list", true);
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
    //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

    var CSV = '';
    //Set Report title in first row or line

    CSV += ReportTitle + '\r\n\n';

    //This condition will generate the Label/Header
    var cols = [];
    if (ShowLabel) {
        var col = [];

        //This loop will extract the label from 1st index of on array
        for (var index in arrData[0]) {

            //Now convert each value to string and comma-seprated
            col.push(index);
        }
        cols.push(col);
    }

    //1st loop is to extract each row
    for (var i = 0; i < arrData.length; i++) {
        var col = [];
        //2nd loop will extract each column and convert it in string comma-seprated
        for (var index in arrData[i]) {
            col.push(arrData[i][index]);
        }
        cols.push(col);
    }

    if (!cols.length) {
        alert("Invalid data");
        return;
    }

    var table = "<TABLE border=1>";
    var col = 0, loop = true;
    while(loop) {
        table += "<TR><TD>"
        var row = [];
        for(var r in cols) {
            loop &= (col < cols[r].length - 1);
            row.push(cols[r][col]);
        }
        CSV += '"' + row.join('","') + '"\r\n';
        table += row.join("</TD><TD>") + "</TD></TR>";
        col++;
    }
    table += "</TABLE>";
    console.log(CSV)
    document.body.innerHTML = table;
}

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

Replicate the anchor's functionality (opening in a new window when 'ctl' is pressed) when submitting a form

I have a question that may seem unconventional - Is there a graceful method to replicate the functionality of an anchor tag when submitting a form? I want users to be able to hold down the control key while submitting a form and have the result open in a ...

Tips for filling jstree with information in Grails

I am currently facing difficulties in populating a jstree within a Grails gsp. Here is what I have attempted so far (rewritten for clarity): <script> $("#treeView").jsTree(); </script> <div id="treeView"> <g:each in="${atomMa ...

Issue encountered while attempting to load JSON data into Hive

JSON data structure is as follows: {"id":"U101", "name":"Rakesh", "place":{"city":"MUMBAI","state":"MAHARASHTRA"}, "age":20, "occupation":"STUDENT"} {"id":"","name":"Rakesh", "place":{"city":"MUMBAI","state":"MAHARASHTRA"}, "age":20, "occupation":"STUDENT ...

Navigating through JSON object array using *ngFor directive in Angular 4

I am trying to iterate through an array of objects stored in my JSON file. JSON [ { "name": "Mike", "colors": [ {"name": "blue"}, {"name": "white"} ] }, { "name": "Phoebe", "colors": [ {"name": "red"}, { ...

Using Ajax on a WordPress webpage

I am currently experimenting with this piece of Ajax jQuery code within a WordPress page: 1. <script> 2. $(document).ready(function(){ 3. $("button").click(function(){ 4. $.ajax({ 5. method: 'GET', 6. ...

Enable compatibility with high resolution screens and enable zoom functionality

My goal is to ensure my website appears consistent on all screen sizes by default, while still allowing users to zoom in and out freely. However, I've encountered challenges with using percentages or vh/vw units, as they don't scale elements prop ...

Validating alpha-numeric passwords with JavaScript

I created a JavaScript function to validate if a password is alphanumeric. However, I am facing an issue where the alert message is not being displayed when the password is not alphanumeric. Below is my code snippet: if (!input_string.match(/^[0-9a-z]+$ ...

What is the process of handling XML responses using node.js and express?

My task is to handle this using node.js and express: <set id="1" state="0" name="wd"/> I attempted the following approach: xml = require('xml'); res.set('Content-Type', 'text/xml'); res.send(xml('<set id="1" ...

Ways to eliminate the initial digit of a decimal number if it is less than 1

I need assistance with modifying float values by removing the first number if it's lower than 1 In the "OPS" table section, I am calculating the sum of OBP and SLG obtained from a database. See the code snippet below: <td>{props.player.OBP}< ...

The initial request is replaced by new information

Trying to fetch data for autocomplete in Laravel. Controller: public function collection_search(Request $request) { $term = $request->search; $serveurapObj = new Serveurap(); $result = $serveurapObj->collectionAutocomplete(); ...

When new AJAX content is loaded, Isotope container fails to properly target the new objects and instead overlaps the existing ones

My webpage loads all content through an AJAX call. Initially, I tried placing my isotope initialization code inside a document ready function, but it didn't work as expected: $(function(){ container = $('#content'); contain ...

Ways to incorporate a loading feature in javascript, jquery, and php as it runs?

I have created a form that, when clicked on, returns a value within the page. Below is my form. When the form is submitted, it takes some time to process. I would like to display a loading message while the code is being executed. Here is my form: <ht ...

Sending a custom `GET` request with multiple IDs and additional parameters using Restangular can be achieved by following

I'm trying to send multiple ids along with other parameters using my custom customGET method. However, the implementation seems to be incorrect: var selection = [2,10,20]; // Issue: GET /api/user/export/file?param1=test&ids=2,10,20 Restangular.a ...

After a page reload, Material-UI stops functioning properly

I am currently working with Material UI in a Next.js project. When I run npm run dev, everything looks good. However, whenever I refresh the page, all the styling breaks. Has anyone experienced this issue before? It seems like Material-UI is no longer func ...

Which file format is most compatible for uploading into MongoDB?

As I am not well-versed with MongoDB, I apologize if my query sounds too basic. In my project, I deal with 4 datasets, each containing files related to samples. Every sample has files for three normalization methods. The total count of samples across all ...

Could JOI be used to validate unidentified keys within nested data structures?

I've developed a middleware that uses Joi to validate incoming requests. export default (schema: any) => async (req: Request, res: Response, next: NextFunction) => { try { const validation = schema.validate(req, { abortEarly: false }) ...

Toggle class to a div upon clicking menu item

Seeking assistance with jQuery to develop a video player featuring a sub menu for displaying various content options upon selection. Here is a snapshot of the frontend design: view image Upon clicking on 'video' or 'audio', a distinct ...

I am currently in the process of verifying email addresses

I attempted to validate multiple email addresses from a txt file and then save the valid emails to another txt file using nodejs. Unfortunately, it did not work as expected. Despite successfully reading the file, all emails were deemed invalid, even though ...

How can I connect the Bootstrap-datepicker element with the ng-model in AngularJS?

Below is the html code for the date field : <div class='form-group'> <label>Check out</label> <input type='text' ng-model='checkOut' class='form-control' data-date-format="yyyy-mm-dd" plac ...

How to sync two carousels in Bootstrap 5 to slide simultaneously with just one click on the next and previous buttons

I am trying to implement dual sliding carousels using Bootstrap 5, but I am encountering issues with getting them to slide simultaneously. Despite incorporating data-bs-target=".carousel", the synchronization isn't working as intended in my ...