Generate a CSV file using Javascript

I am working with an HTML table (table id='testTable') and a button in the HTML code:

 <button id="btnExport" onclick="javascript:xport.toCSV('testTable');">CSV</button>

There is also JavaScript code involved:

toCSV: function(tableId, filename) {
var date=new Date();
this._filename = (typeof filename === 'undefined') ? tableId :      filename;
// Generating CSV string from HTML Table
var csv = this._tableToCSV(document.getElementById(tableId));
// Creating a CSV Blob
var blob = new Blob([csv], { type: "text/csv" });

// Determining the download approach
if (navigator.msSaveOrOpenBlob) {
  // Works for Internet Explorer and Microsoft Edge
  navigator.msSaveOrOpenBlob(blob, this._filename + ".csv");
} else {      
  this._downloadAnchor(URL.createObjectURL(blob), 'csv');      
}
}


_tableToCSV: function(table) {
// Using `slice` to create arrays
var slice = Array.prototype.slice;

return slice
  .call(table.rows)
  .map(function(row) {
    return slice
      .call(row.cells)
      .map(function(cell) {
        return '"t"'.replace("t", cell.textContent);
      })
      .join(",");
  })
  .join("\r\n");
}

I want to update the filename to the current date. How can I achieve that?

Answer №1

Modify toCSV to the following:

toCSV: function(tableId, filename) {
    var date = new Date();
    this._filename = (typeof filename === 'undefined') ? date : filename;
    // Convert HTML Table to CSV string
    var csv = this._tableToCSV(document.getElementById(tableId));
    // Create a CSV Blob
    var blob = new Blob([csv], { type: "text/csv" });

    // Determine which method to use for the download
    if (navigator.msSaveOrOpenBlob) {
        // Suitable for Internet Explorer and Microsoft Edge
        navigator.msSaveOrOpenBlob(blob, this._filename + ".csv");
    } else {
        this._downloadAnchor(URL.createObjectURL(blob), 'csv',this._filename);
    }
}

Change _downloadAnchor to the following:

_downloadAnchor: function(content, ext, filename) {
    var anchor = document.createElement("a");
    anchor.style = "display:none !important";
    anchor.id = "downloadanchor";
    document.body.appendChild(anchor);

    // Attempt to use [download] attribute if supported

    if ("download" in anchor) {
        anchor.download = filename + "." + ext;
    }
    anchor.href = content;
    anchor.click();
    anchor.remove();
}

Answer №2

  _createDownloadLink: function(data, format) {
    var link = document.createElement("a");
    link.style = "display:none !important";
    link.id = "downloadlink";
    document.body.appendChild(link);

    // Check if the browser supports the download attribute

    if ("download" in link) {
      link.download = this._filename + "." + format;
    }
    link.href = data;
    link.click();
    link.remove();
   }

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

Splicing using only one parameter will make changes to the array without deleting the entire array

let myArray = ['a','b','c','d','e']; console.log(myArray.splice(1)); console.log(myArray); Looking at the splice documentation, it mentions that not providing a delete parameter would remove all array item ...

What steps should I take to fix the error "Unused left side of comma operator with no side effects.ts(2695)" in my React project?

import React from "react"; import { useRecoilState } from "recoil"; import { Industry, industryState } from "../atoms/industriesAtoms"; const manageIndustryData = () => { const [industryStateValue, setIndustryStateValue] ...

Tips for showcasing the chosen option from an autocomplete input field in a React application

Currently learning React and working on a search feature for a multi-form application. The goal is to allow users to search for a student by first name, last name, or student ID using an autocomplete text field. The options for the autocomplete text field ...

Uncovering the unique properties of custom Items in MUI v5 - RichTreeView: A Step-by-Step Guide

Can custom item properties received asynchronously with MUI - RichTreeView be exposed inside a custom treeItem? For instance, how can the customProperty1 and customProperty2 be accessed within the CustomTreeItem? The console.log to props only shows defaul ...

Developing a counter/timer feature in a web application using PHP and MySQL

I am currently working on a form that submits data to a database with the possibility of the issue being either 'resolved' or 'notresolved'. My goal is to create a timer that starts counting as soon as the form is submitted and the issu ...

Adding up values of objects in a different array using Vue.js

Recently, I started using VueJs and encountered an object that contains arrays. One of the tasks I need to accomplish is to display the total sum of all amounts in one of the columns of the table. Here is my table structure: < ...

Errors encountered in the ajax request, specifically 404 and 401 errors

Using jQuery's ajax method, I am submitting an ajax request in the following manner: $.ajax({ type: "PUT", url: specifiedURL, contentType: "application/json", data: JSON.stringify(data), dataType: "json" ...

Is it possible for a React blog to be included in search engine results?

As I work on building my blog using React, Node.js, Express, Sequelize, and other technologies, a question has arisen in my mind: Will search engines index my articles, or will only the homepage of my site be noticed? For instance, if I have an article ti ...

Issue TS7053 occurs when trying to access any index of the target of a React.FormEvent<HTMLFormElement>

I've been working on adapting this tutorial to React and TypeScript. Here is the code snippet I have implemented for handling the onSubmit event: const handleSignUp = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); ...

Dynamic Visibility Control of GridPanel Header in ExtJS

I have a GridPanel that needs to display a limited number of resources. If there are more resources available than what is currently shown, I would like the panel's header/title to indicate this by displaying text such as "more items available - displ ...

Tips for showing the value in the subsequent stage of a multi-step form

Assistance is required for the query below: Is there a way to display the input field value from one step to the next in multistep forms? Similar to how Microsoft login shows the email in the next step as depicted in the image below: ...

"Enhance Your Sublime 3 Experience with a Jade Syntax Highlighter, Linting, Auto Complete, and

After trying out the recommended packages for Sublime Text, I'm still not satisfied with how they handle syntax highlighting, code linting, and auto suggestion. Could anyone recommend a comprehensive package specifically for Jade? ...

Getting rid of a texture in three.js

I am attempting to deallocate a texture once it has been loaded in three.js. The texture is loaded using var tex = THREE.ImageUtils.loadTexture("image.png"); and it is being displayed correctly. However, when I attempt to use: tex.dispose(); I consist ...

Closing the Bootstrap navbar collapse by clicking anywhere outside of the menu area

Excuse my lack of experience, but I have a question. I am trying to make Bootstrap "navbar-collapse" close when clicking away or on one of the list items. I stumbled upon this code that seems to do the trick. $(document).on('click',function() { ...

Having trouble with creating a new Next.js app using the latest version with npx?

Having some difficulty with the "npx create-next-app@latest" command while setting up Next.js. As a newcomer to both the community and Next.js, I could use some assistance in resolving this problem. Upon running the command, an unfamiliar message was displ ...

What's the best way to dynamically show Bootstrap collapse panels in a loop with AngularJS ng-repeat?

Currently, I am utilizing angularJS and attempting to include a bootstrap collapsible-panel within a loop. The code that I have written is causing all the panel bodies to be displayed beneath the first panel header. I need each body to be shown below i ...

When querying a MongoDB object in Node.js, the inner value may sometimes return as undefined

After retrieving a store object from MongoDB, my focus shifted to utilizing the value stored in store.comments. Upon logging the store value, here is what I found: store:{ _id: 57e246f73e63d635cce3d174, __v: 0, comments: 57e246f73e63d635cce3d177, l ...

There seems to be a contradiction in my code - I am returning a Promise but TypeScript is throwing an error saying that the

I currently have a function that retrieves a bot's inventory on the Frontend fetchBotInventory() { this.socket.emit('fetch bot inv'); this.socket.on('bot inv', (botInventory) => { return new Promise((resolve, re ...

Using React for form validation

I'm facing a challenge while trying to develop a user registration form, especially when it comes to displaying form validation errors. Issues: 1) The input fails to post (via axios) to the database upon submission for inputs without errors. 2) The e ...

Is it possible to set a different default page index other than 0 in a material table using reactjs?

I have noticed that the default page index in the material table is set to '0', but the API I am currently using begins with a page index of '1'. Is there a way to adjust the default page index of the table to match that of the API? ...