Styling hyperlinks upon exporting an HTML table to Excel

I am trying to export an HTML table to Excel using JavaScript by following the instructions provided in Export HTML table to Excel its downloading table contents to the Excel.

However, I have encountered an issue where one of the columns in my table contains links. When I export the table to Excel, the content in that column appears as hyperlinks in the Excel sheet. I would like to export the table to Excel without these links, showing just plain text instead.

Is there a way to achieve this?

Answer №1

If you need to update all the linked text with plain text.

Replicate the table that needs to be exported

table = $('#'+tableName).clone();

Swap the anchor tag with the corresponding span

 var sp1 = document.createElement("span");
 var sp1_content = document.createTextNode($(hyperLinks[i]).text());
 sp1.appendChild(sp1_content);
 var sp2 = hyperLinks[i];
 var parentDiv = sp2.parentNode;
 parentDiv.replaceChild(sp1, sp2);

More information on how to replace a node can be found here.

Using the code provided in this Stackoverflow answer for exporting.


Check out the code snippet on PEN

var tmp;
function strip(html) {
  tmp = document.createElement("DIV");
  tmp.innerHTML = html;
  console.log(tmp.innerText);
  console.log(tmp.textContent);
  
  return tmp.textContent || tmp.innerText || "";
}

var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,',
    template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
    base64 = function(s) {
      return window.btoa(unescape(encodeURIComponent(s)))
    },
    format = function(s, c) {
      return s.replace(/{(\w+)}/g, function(m, p) {
        return c[p];
      })
    }
  return function(table, name, filename) {
    if (!table.nodeType) 
    
    /*Clone the table that is to be exported*/
      table = $('#'+table).clone();
    
    
    
    var hyperLinks = table.find('a');
    
    
    
    for (i = 0; i < hyperLinks.length; i++) {
          
      //hyperLinks[i] =  $(hyperLinks[i]).text();
          var sp1 = document.createElement("span");

          // give it an id attribute called 'newSpan'
          sp1.setAttribute("id", "newSpan");

          // create some content for the new element.
          var sp1_content = document.createTextNode($(hyperLinks[i]).text());
          console.log(sp1_content);
          // apply that content to the new element
          sp1.appendChild(sp1_content);

          // build a reference to the existing node to be replaced
          var sp2 = hyperLinks[i];
          var parentDiv = sp2.parentNode;

          // replace existing node sp2 with the new span element sp1
          parentDiv.replaceChild(sp1, sp2);
      }
    
    
    
      var ctx = {
        worksheet: name || 'Worksheet',
        table: table[0].innerHTML
      }
    

    document.getElementById("dlink").href = uri + base64(format(template, ctx));
    document.getElementById("dlink").download = filename;
    document.getElementById("dlink").click();

  }
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="dlink" style="display:none;"></a>

<table name="tablename" id="tablename" border="1">
<tr>
  <td>1</td>
  <td><a href="http://google.com">google</a></td>
  </tr><tr>
  <td>2</td>
  <td><a href="http://microsoft.com">microsoft</a></td>
  </tr><tr>
  <td>3</td>
  <td><a href="http://amazon.com">amazon</a></td>
  </tr>
</table>

<input type="button" onclick="tableToExcel('tablename', 'name', 'myfile.xls')" value="Export to Excel">

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

How to set the default value for an angularJS select dropdown

Can someone assist me with setting a default value for a select dropdown using AngularJS? I have explored similar threads on StackOverflow, but none of the suggested solutions have resolved my issue. Therefore, I am reaching out to seek help here. Essenti ...

The requested `GLIBC_2.28' version required by node cannot be located, leading to an inability to amplify the version

While there were numerous questions about this topic, I am specifically seeking solutions for amplify. Below are the logs from my amplify build: 2024-01-14T16:14:17.626Z [INFO]: # Cloning repository: <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Awaiting the completion of Promises within a for-loop (Typescript)

I'm struggling with a for-loop and promises in my angular2 project. I have multiple methods that return promises, and after these promises are resolved, I want to populate an array in the class using Promise.all(variable).then(function(result){....... ...

Do you have any queries regarding JavaScript logical operators?

I'm struggling with understanding how the && and || operators work in my code. I created a small program to help myself, but it's just not clicking for me. The idea is that when you click a button, the startGame() function would be triggered. va ...

How can you implement CSS styling for Next.js HTML during server-side rendering?

Explore Next.js and observe the page request in the network tab. The preview displays not only the HTML but a fully pre-styled page as well. https://i.stack.imgur.com/deJLY.png When working with Styled-Components and Material-UI, they offer the ServerSty ...

Adding an element within an ngFor iteration loop

I'm currently working on a code snippet that displays items in a list format: <ul> <li *ngFor="#item of items">{{item}}</li> </ul> These items are fetched from an API through an HTTP call. Here's the code snippet for tha ...

Tips for splitting the json_encode output in Javascript

Looking for help with extracting specific values from JSON data retrieved via PHP and AJAX. I only want to display the agent name in my ID, not the entire object that includes "name" : "Testing". Here is the console output: [{"agent_module_id":"1","agen ...

Ensure you are focusing on elements exclusively contained within the parent table and not any child tables nested within its cells

Looking for some help with a unique situation here. I'm struggling to find the right selector for this task. For reference, you can check out the jsfiddle at this link: http://jsfiddle.net/NZf6r/1/ The scenario is that I have a parent table containin ...

Moving a component beyond its container using a query

After much searching, I have yet to find a solution to fix this issue. My problem involves having a list with draggable elements within a scrollable area. The goal is to drag these elements outside of the parent div into a droppable area; however, they see ...

Node.js application experiences a crash upon entering incorrect credentials

Would you mind reviewing my Login Function? After entering incorrect credentials, a response is sent but unfortunately the app crashes The versions I am using are Express ^4.17.2 and Node.js v16.14.0 router.post( "/login", [ body(" ...

What is the best way to position a small image within a menu?

Is there a way to adjust the position of the arrow image within the <li> element without affecting the layout of the unordered list? Below is the code snippet for reference: body { margin: 0; padding: 0; } nav { width: 100%; background: # ...

Resetting the index and length in Vue.js each time a new page is loaded

Currently facing an unusual issue that I'm struggling to resolve. My goal was to include an index number in a for-each loop and calculate the total count of data within my vue.js component. While I successfully achieved this, I encountered a problem w ...

Tips for creating a unique exception in AngularJS?

I have a customException.js script with the following service: app.service('CustomException', function() { this.CustomException1 = function (message) { if (!message) { message = "Custom Exception 1 occurred!"; } return { ...

How to access the public folder in React from the server directory

I am having an issue with uploading an image to the react public folder using multer in NodeJs. Everything was working fine during development, but once I deployed it, the upload function stopped working. It seems like the multer is unable to reference or ...

Learning to Use jQuery to Send JSON Requests in Rails

I am attempting to send a JSON post request to a Rails 3 server. Here is the AJAX request I have set up: $.ajax({ type: 'POST',<br> contentType: "application/json",<br> url: url, ...

Error code 1 occurs when attempting to execute the "npm run start" command

Every time I attempt to execute "npm run start" within my project folder, the following error message pops up: myLaptop:app-name userName$ npm run start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1a0b1b1ecafa0aca481f ...

Can you show me the steps for downloading the WebPage component?

My goal is to save webpages offline for future use, but when I download them as html many of the included components disappear! I attempted opening them in a WebBrowser and downloading as html with no success. One potential solution is to download the ht ...

Using the fetch/await functions, objects are able to be created inside a loop

In my NEXTJS project, I am attempting to create an object that traverses all domains and their pages to build a structure containing the site name and page URL. This is required for dynamic paging within the getStaticPaths function. Despite what I believe ...

Trying out asynchronous testing using Mocha and Sinonjs for the first time

In my current project, I am utilizing a custom micro framework developed by our team, where we make use of Mongoose. To handle the mongoose object, we have implemented a modelfactory that provides us with a corresponding model based on the mongoose name o ...

Focusing on a particular iframe

I am currently using the "Music" theme from Organic Theme on my WordPress site and have inserted this code to prevent SoundCloud and MixCloud oEmbeds from stretching the page width: iframe, embed { height: 100%; width: 100%; } Although the fitvid ...