Tips on exporting an html table to an excel sheet with the click of a button, without relying on php

How can I export this HTML table to an Excel file using JavaScript and CSS only, without the use of PHP? Please provide the complete code along with the required links to the JavaScript files.

<table id="tb1">
    <tr>
        <td>Product</td>
        <td>Price</td>
        <td>Available</td>
        <td>Count</td>
    </tr>
    <tr>
        <td>Bred</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tr>
        <td>Butter</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
    </tr>

Answer №1

If you want to achieve it, simply embark on a journey of exploration and study. Here are some suggestions for you to consider and adapt the codes according to your requirements.

This technique is compatible with IE7+, Firefox, Chrome, and Safari. Below is the JavaScript code:

function ToExcelReport(){
    var tab_text="<table border='2px'><tr bgcolor='#FFFFFF'>";
    var textRange; var j=0;
    tab = document.getElementById('tb1'); //id of table

    for(j = 0 ; j < tab.rows.length ; j++){     
        tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
    }

    tab_text=tab_text+"</table>";
    tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
    tab_text= tab_text.replace(/<img[^>]*>/gi,""); //remove if u want images in your table
    tab_text= tab_text.replace(/<input[^>]*>|</input>/gi, ""); //remove input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){
        //if Internet Explorer
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa=txtArea1.document.execCommand("SaveAs",true,"Sample.xls");
    } else{
        //other browsers
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  
    }

    return (sa);
}

Create an empty iframe:

<iframe id="sample" style="display:none"></iframe>

Then design a button that triggers the export process. (It's up to you)

<button id="btnExport" onclick="ToExcelReport();"> EXPORT </button>

Here's another approach using jQuery. This method involves using jquery in conjunction with the JQuery DataTables Table Tools plugin. Keep in mind that this may not function correctly without flash support.

$(document).ready( function () {
    $('#tb1').dataTable( {
        "sDom": 'T<"clear">lfrtip',
        "oTableTools": {
            "sSwfPath": "/swf/copy_cvs_xls_pdf.swf"
        }
    } );
} );

Lastly, one of the most effective ways is to utilize server-side languages. Sometimes, dealing with client-side languages can be challenging in situations like this. If you're open to new perspectives and willing to make a change, consider using PHPExcel :)

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

Working together: combining ngMessages with a datepicker

In my Angular project, I am utilizing ngMessages for form validation and am encountering an issue when using it with a Datepicker. After selecting a date, the ng-message does not disappear, indicating that ngMessages is not detecting any events being tri ...

Tips on confirming the completion of my form when the next button is pressed

I am working on a multi-step form with a jQuery script to split the forms. The first form has only one button - the next button, which takes the client to the next form. However, when I click on the next button in the first form, it moves to the next form ...

Webpack automatically prepends "auto/" to script tags in the compiled HTML file

I am currently setting up an application for coding, but I am facing a problem with webpack. Every time I build the application, webpack automatically adds "auto/file.js" to the script tags instead of just "file.js". I have checked all my webpack configura ...

I'm receiving the error message "app.get is not a function" when using Express.js. What could be

Having trouble understanding why I am getting an error: app.get is not a function in the upload.js file with the provided code snippet. In my index.js file, I have set up everything and exported my app using module.exports = app. I have also used app.set( ...

Encountering a repetitive setState issue within an array in Next.js

I'm struggling to find a solution for my issue - everything loops correctly the first time, but after looping twice in the array I encounter an error "TypeError: props.imgData[index] is undefined". Below is the code snippet : import React, { useEffec ...

What is the quickest method to identify duplicate entries within a JavaScript array?

let items = ['test0','test2','test0']; In the scenario shown above, we have two duplicate elements with the value "test0". What is the most efficient way to check for this duplication? ...

How to incorporate an image within a div element without reliance on the <img> tag

I am dealing with HTML content <div> <img src="xyz.jpg"> </div> The challenge I am facing is fetching an image in hex format from a web service, converting it to JPEG, and displaying it inside a div. However, the <img src=""> ta ...

Retrieve a pair of columns from the database by utilizing SQLalchemy

Currently, I am delving into Python and endeavoring to generate a drop-down menu within my form by utilizing data from another table. Here is the code snippet I have been working on: In my Models.py file: class empmasterModel(db.Model): __tablename__ ...

``"Please dial the number for technical assistance regarding the issue with 'C:Program Files odejs ode.exe'."

I've been attempting to install Node.js and Browser Sync, but I keep encountering an error message. C:\Users\Aly>npm install -g browser-sync 'CALL "C:\Program Files (x86)\nodejs\\node.exe" "C:\Program Files ...

Parsing a Table in Python with HTMLParser

I am trying to convert an HTML table into a 2D array (rows and columns) using only the HTMLParser library in Python, without relying on BeautifulSoup or other non-standard libraries. This task is part of a personal project that I am working on for fun :) ...

JavaScript function that fetches data from local storage and displays it in an HTML table

I've been exploring how to incorporate a bootstrap datatable into my project. Rather than using pre-set data, I want to allow users to input their own data through a form and store it in localStorage. Understanding that I need to stringify and parse ...

Display PDF in Forge Viewer using PDF Extension - warning generated by pdf.worker.js

Whenever we attempt to display a PDF file using our own API, the pdf.worker.js generates a warning message and the PDF always appears completely white. https://i.stack.imgur.com/IqGML.png All I can see is this (it's a wide PDF that renders fine in t ...

Utilizing Jquery UI in Visual Studio 2012 for developing asp.net webforms applications

Recently upgraded to 2012 and encountering some difficulties with implementing a jQuery UI accordion in my default.aspx page. Here is the code snippet from my default.aspx page: <div id="accordian"> <div> <div> ...

Combining Columns into Rows in an HTML Table

Utilizing Rowspan and Colspan to Construct HTML Tables. I am looking to have the first five columns in a single row with no data, as illustrated in the editable image. This can be done using rowspan or colspan. The last two columns should remain unchange ...

Error: dbg variable is not defined in AngularJS

I'm currently in the process of learning angularjs by following a tutorial from this source Take a look at my index.jsp below - <!doctype html> <html lang="en" ng-app="phoneCatApp"> <head> <title>Angular Example</title> ...

Tips for successfully transferring the nested service and retrieving the response from an Angular factory to a controller

After making the Http Request and receiving the response from the first Service call, I then pass that response from the first service into the second service and receive the response back to the controller. Now that I have the response, I need to find a ...

Which format to use for identifying a point within a polygon: JSON or KML

I am currently debating whether to use json or kml for storing polygons in a server file. The ultimate goal is to read this file and determine which polygon a specific point falls within. My initial inclination leans towards kml due to its efficiency in re ...

Retrieve dual JSON objects simultaneously using the AJAX method in jQuery

I am facing an issue where I am trying to return two JSON objects, but only one is being received. The variable 'success' is displaying as a string 'success' when I try to alert it; however, in Firebug, its value is true. Therefore, the ...

Explain the functioning of the Node.js event loop and its ability to manage numerous requests simultaneously

Recently, I delved into testing asynchronous code in node.js. From what I understand, when there is an asynchronous operation taking place, Node.js should be able to handle new requests. Below is a snippet of code I wrote using express and axios: app.get(& ...

Summing Up Values in Jquery Loop Through Table Rows

I am facing a challenge with a table that contains a textfield for inputting numeric values. This textfield is part of a repeated row table, with the ID 'amount'. My goal is to calculate the sum of all values entered in the textfields with the ID ...