JavaScript exporting data to Excel and populating the top row with column

My code successfully exports a file via Excel without any errors. However, the issue I'm facing is that the exported Excel file contains a lot of unnecessary spaces.

The problem is highlighted in the image provided: data from row 123 should be in column 7 but it appears misplaced.

Below is the code snippet responsible for exporting the data:

export function download() {
    var header = [];
    var finalData = [];
    var group = [
        { "group_name": "123" },
        { "group_name": "123b" },
        { "group_name": "123ef" },
        { "group_name": "Accounts Payable" },
        { "group_name": "ADG JET TEAM" },
        { "group_name": "001 Approval" }
    ];
    var member = [
        {"001 Approval": "083817 - Ranjeet Kumar (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86f4e7e8ece3e3f2a8edf3ebe7f4b5c6e5e9e8e5e3e8f2f4effea8e5e9eb">[email protected]</a>)"},
        { "001 Approval": "C01747 - Abid Shaikh (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bddcdfd4d993ced5dcd4d6d58cfdded2d3ded8d3c9cfd4c593ded2d0">[email protected]</a>)"},
        { "001 Approval": "C01747 - Abid Shaikh (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="41202328256f322920282a297001222e2f22242f353328396f222e2c">[email protected]</a>)"},
        { "123b": "C01747 - Abid Shaikh (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9b8bbb0bdf7aab1b8b0b2b1e899bab6b7babcb7adabb0a1f7bab6b4">[email protected]</a>)"},
        {"123ef": "C01747 - Abid Shaikh (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d1c1f1419530e151c1416154c3d1e12131e1813090f1405531e1210">[email protected]</a>)"}
    ];

    group.forEach(data => {
           // Pushing group names to the header
        header.push(data.group_name);
    });

      // Pushing headers to finalData array
    finalData.push(header);

    // Looping through headers to match with members and grab data corresponding to each header
    header.forEach(headerData => {
        var temp = [];
        member.forEach(memberData => {
            if (headerData === Object.keys(memberData)[0]) {
                temp.push(memberData[Object.keys(memberData)[0]]);
            } else {
                temp.push("");
            }
        });
      
     //Pushing resulting data into the finalData array
        finalData.push(temp);
    });

    // Calling exportToCsv function to generate CSV file
    exportToCsv('export.csv',finalData);
}

You can find the exportToExcel code here.

Answer №1

When opening your CSV file in a text editor, make sure to check the separator and delimiter being used. You may encounter issues with formatting such as fields not being enclosed in quotes or problems with how Excel is configured for delimiters and separators.

For example, if your data looks like this:

field1, field2, field 3 supercool, this is a phrase, ops

It should ideally be formatted like this:

"field1", "field2", "field 3 supercool", "this is a phrase, ops"

Try opening your CSV file in Google Sheets (docs) as well, as it can automatically detect delimiters and separators. Test to see if this resolves any issues you may be experiencing.

A common problem arises when the CSV is separated by spaces or commas, but certain phrases contain both a space and a comma, which disrupts the document's structure.

For additional assistance, refer to this helpful link: Write a string containing commas and double quotes to CSV

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

Retrieve all possible permutations from an array using PHP

I am working with an array and would like to find all possible unique combinations. Here is an example: $array = ['A', 'B', 'C', 'D'] The desired result should look like this: $new_array = [ ['A', &apo ...

Why does my Redux callback keep getting invoked multiple times?

In developing a react application with redux, I have chosen to avoid using react-redux by manually handling all dispatched events. Below is a sample code snippet. The content of index.html <!DOCTYPE html> <html> <head> <script src=& ...

Using jQuery Datatables fnReloadAjax successfully triggers a reload of the data, however, it

In my jQuery datatable, I am utilizing the code below to refresh the data: $(".unread-rows").click( function(e) { e.preventDefault(); message_table.fnReloadAjax("/letters/ajax/inbox/1"); message_table.fnDraw(); $(this).addClass("active").s ...

Why does Asp.net Webform load twice every time I click on the form link?

In my asp.net webform project, I am encountering an issue where the page is running twice when clicked. The problem arises when calling two functions (Fill DropDowns) on the Page_Load Event. During debugging, it was observed that the control enters the Pa ...

Tips for encoding a base64 string into formats such as PDF, doc, xls, and png using jQuery, JavaScript, and HTML5

Need help handling base64 strings received from the server to save files in multiple browsers (IE, FF, Chrome). If receiving a PDF base64 string, how can it be saved in the browser? Also, if receiving an Image or Doc base64 string, what is the process fo ...

Review the Drawer Item's Render Method

I have been using react-native with expo and following a specific guide closely: Is there an alternative way to implement this without the use of icons at the moment? Upon compiling, I encountered an error regarding the Render Method of DrawerItem. I&apo ...

Tips for filtering data using an array within an object containing arrays

Below is the provided information: userRoom = ['rm1']; data = [{ name: 'building 1', building: [{ room: 'rm1', name: 'Room 1' },{ room: 'rm2', name: ' ...

What is the method for obtaining a dynamic image URL for the <a href> link?

Here is the default Wordpress generated code for displaying images: <div class="image-section"> <a href="http://websitename.com/wp-content/uploads/2019/06/image-1.jpg" target="_blank" rel="noopener noreferrer"> <img src="http://websit ...

Ember Data's counting model feature

After searching through numerous examples on Stackoverflow, I am still struggling to grasp the concept of how get('length') functions. I am attempting to retrieve a user count in the helper model. The issue may lie in my approach to using get(&a ...

Leveraging Jquery Splice

Trying to eliminate an element from an array using the Splice method. arrayFinalChartData =[{"id":"rootDiv","Project":"My Project","parentid":"origin"},{"1":"2","id":"e21c586d-654f-4308-8636-103e19c4d0bb","parentid":"rootDiv"},{"3":"4","id":"deca843f-9a72 ...

Using Node.js with Express to seamlessly pass objects to EJS templates

I have a scenario where I am passing an object to my template and I want to display the details of that object in HTML. app.get('/', function (req, res) { var user = req.session.passport.user; if ( user != 'undefined' ){ ...

Unable to implement new ecmascript decorators within typescript version 2.4.2

Check out this example code: function enumerable(value: boolean) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { descriptor.enumerable = value; }; } class A { @enumerable(false) a: number = 1 b: number ...

The type 'number' cannot be assigned to an empty object

New to TypeScript and seeking assistance. I recently refactored a colleague's code and implemented TypeScript. Since then, I have been fixing bugs, but I am stuck on one particular issue. Any help would be greatly appreciated! Within this component, ...

What is the alternative method for reading an HTML text file in JavaScript without utilizing the input type file?

Within the assets folder, there is a text file containing HTML that needs to be displayed within a specific component's div. Is it possible to retrieve the contents of this file and assign them to a string variable during the ngOnInit lifecycle hook ...

What is the recommended approach for sending a null value to a mandatory property in a Vue.js component?

Setup: Vue.js (3.2) with Composition API, TypeScript, and Visual Studio Code File type.ts: export class GeographicCoordinate { latitude: number; longitude: number; altitude?: number; constructor(latitude: number, longitude: number, altitude?: num ...

"Troubleshooting: Issues with message passing between popup.html and content.js in Chrome Extension

I'm facing a challenge in creating an Extension that transfers data from popup.html to the tab dome. Unfortunately, I am having trouble with getting the sendMessage function to work and I can't figure out why. I'm using the following guideli ...

bulk purchase discount with HTML/JavaScript/PHP

I am looking to add a slider feature to my "Prices" page in order to provide customers with an instant quote based on the quantity they select. The slider should range from 1 to 500 or even up to 1000, but having an input box for customers to enter the qu ...

Mastering the art of accessing properties in typescript post implementing Object.defineProperty

I was experimenting with the TypeScript playground trying to figure out decorators and encountered some questions. class PathInfo { functionName: string; httpPath: string; httpMethod: string; constructor(functionName: string, httpPath: str ...

Utilizing Nested ControlGroups in Angular2 rc1: A Comprehensive Guide

Seeking assistance with understanding the functionality of a control group. Attempting to implement something similar to this: app.component.ts: import { Component, OnInit } from "@angular/core"; import { FORM_DIRECTIVES, FormBuilder, ControlGroup } from ...

Centralized MUI design for varying screen dimensions

I am struggling to perfectly center my modal box in the middle of the screen. The problem arises when the screen size changes, causing the box to be misaligned. I attempted using top:50% and left: 50%, but this did not effectively center the box. center ...