Having trouble downloading an Excel file with custom headers. Can anyone help me solve this issue?

Currently, I am exporting an excel file for a client user where the user enters their data based on the corresponding headers in the excel file. Once the user completes entering their data, they upload the excel back to the system. The issue I am facing is that when the headers are downloaded, they appear in a single column separated by commas. My requirement is to have each header in a unique single column as shown in this example: https://i.sstatic.net/sfZht.png

I need the headers to be displayed like this: https://i.sstatic.net/Wljw5.png. Below is my code snippet:

$scope.DownLoadTemplate = function () {

    for (a in $scope.SalaryHeadList)
    {
        $scope.HeadTitle = $scope.SalaryHeadList[a].Title;
        $scope.HeaderList.push(angular.copy($scope.HeadTitle));
    }
    $scope.CurrencyTitle = $scope.CurrencyList[0].Title;
    $scope.HeaderList.push(angular.copy($scope.CurrencyTitle));

    var url = window.URL.createObjectURL(new Blob([$scope.HeaderList]));
    var link = document.createElement('a');
    var filename = "Employee.xls";
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
}

Please help me resolve this issue!

Answer №1

$scope.exportData = function () {
    debugger;
    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>{CouponDetails}</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]; }) }

    var table = document.getElementById("example1");
    var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML };
    var url = uri + base64(format(template, ctx));
    var a = document.createElement('a');
    a.href = url;
    a.download = 'Expoerdata.xls';
    a.click();
};

HTML table content:

<table id="example1" class="table table-bordered invoice-custom example1" 
       style="display:none;">
    <thead>
        <tr>
            <th data-field="id">Sno</th>
            <th data-field="name" data-editable="true">Name</th>

            <th data-field="phone" data-editable="true">Value</th>

            <th data-field="action">Edit</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="Test in allItems | orderBy:TestParams_Id:reverse">
            <td style="text-align:center">
                {{Test.sno}}
            </td>
            <td>{{Test.Name}}</td>
            <td>{{Test.ExpectedValue}}</td>
        </tr>
    </tbody>
</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

Guide to turning off alerts for identifiers starting with an underscore (_)

Exploring ReactJS Development with ESLint Being a developer working with ReactJS, I find great value in the automated assistance provided by ESLint for detecting code issues like unused identifiers. If you're interested in experimenting with ESLint, ...

Downloading a PDF file received from a Django view using JavaScript and jQuery

I have a celery task that creates PDF files on the click of a button. When the button is clicked, the JavaScript side will keep checking until the task is done, and when it is, it will download the file. Some recursion should do the trick: $(".getPdf").o ...

Vercel and Firebase Realtime Database causing snapshot.val() to return null during build deployment

Creating a blog application using Next.js, Firebase Realtime Database, and Vercel for hosting has been seamless on my local machine. Even after running npm run build, everything functions perfectly. However, when deployed to Netlify in production, the snap ...

"Adding dots" in a slideshow using HTML, CSS, and JS

I'm currently working on a slideshow that includes navigation dots at the bottom. Although the slideshow is functioning properly, I am encountering an issue where only one dot appears instead of the intended three in a row. Despite my research and att ...

Transforming the express app object into a data type instead of a regular variable

Currently, I am setting up my own TypeScript Express project and aiming to abstract the code for better organization. In my app.ts file, the code looks like this: import express from 'express' const app = express(); const port = 3000; require( ...

Tips for integrating icons with React's slick slider functionality

There's a piece of code that showcases various icons. switch (name) { case Header.Arrows.name: return <ArrowsComponent key={name} color={color}/>; case Header.Zoom.name: return <ZoomTool key={name} color={color}/>; ...

The current status of Dropzone.js is in a pending state, preventing the upload of any

I have integrated Multer in the back-end for file upload handling and Dropzone.js in the front-end. Testing my back-end code with Postman works perfectly, but when using Dropzone, the status remains pending and the file does not get uploaded. After waiting ...

What is the reason behind Bootstrap 5's decision to have the getOrCreateInstance() method automatically toggle the collapsible element upon creation?

Today was my first encounter with the Collapse feature in Bootstrap 5, and I have to admit, I am not a fan! Imagine a scenario where I have a collapsible element that is initially hidden, and a button to toggle its visibility, like so: <button class=&q ...

What is the method to obtain an object as the return value from a click function in JavaScript?

I would like to retrieve the cell value from a table by clicking on a button. I have already created a function called getDetail in JavaScript that is implemented on the button, but I am facing difficulty in returning the value from the function. <butto ...

What happens when AngularJS encounters real-time polymorphism during runtime?

An intriguing report by the Financial Times discusses how Shape Security, a Google-backed venture, is using shape-shifting code to outsmart hackers. Real-time polymorphism could revolutionize cyber security, attracting investors from major tech companies l ...

The categorizing and organizing of arrays

My goal is to create a messaging application where users can view a list of their recent messages, along with a preview of the latest message received/sent, before selecting a conversation. However, I'm facing an issue with my script that displays all ...

What is the best way to conceal content when the user clicks on the "more" button?

My HTML Code includes the following structure: ... @foreach($hotel as $key=>$value) ... <div class="iteration"> <input type='hidden' value='<?php echo $value['HCode& ...

Attempting to select an image with the intention of triggering a modal to appear through an ajax

Hi there, I recently started coding and I'm facing an issue that I can't seem to solve. I want to set it up so that when you click on an image, a modal opens corresponding to the img tag, and then the modal click event triggers a method. The prob ...

Sending AJAX data from VIEW to CONTROLLER in PHP (MVC) using AJAX: A step-by-step guide

I have a page at http://visiting/blog. The Controller contains two methods: action_index and add_index. When Action_index() executes, it returns pages with indexes. On the other hand, Add_index() invokes a model's method called add_data(), which inse ...

The use of the 'v-on' directive with the 'KeyboardEvent.keyCode' modifier is no longer recommended in Vue. It is now recommended to use 'KeyboardEvent.key' instead

I am currently in the process of upgrading my Vue 2 application to Vue 3. However, when I run the application, I encounter some deprecation errors. Previously, I used numbers and "key" in my keyboard event modifiers. This approach is now deprecated in Vue ...

The Function(JS) is specifically designed to only function within the topmost div or quote

Currently, I am facing an issue with a function I have implemented. This function adds a blur effect to words in a Blockquote when the page is loaded. However, I need this function to work for all Blockquotes and different divs on the page, not just the to ...

When should the preloader be placed within the DOMContentLoaded or load event?

I'm looking to implement a preloader on my website to ensure everything is fully loaded - images, JavaScript, fonts, etc. However, I'm unsure whether to use the following: window.addEventListener('DOMContentLoaded', () => { // code ...

Ways to update the page content seamlessly without refreshing the page

Is there a way to dynamically change the content of a specific div (such as: <div id="MyDiv"></div>) on a webpage using PHP when clicking a link? Previously, I attempted the following approach: $(function(){ $("a").on("click", function () ...

Executing a Javascript function post AJAX page loading

I'm not a coding expert, so I hope my question is still clear. Essentially, I have an index.php page with filters (by project, year, month) that send variables to filterData.php after clicking submit. These variables are then used in SQL statements t ...

Fetching data dynamically using ajax as you scroll

Currently, I am using the jQuery Tools Plugin to create an image slider. However, I am facing a challenge with loading a large number of images all at once. Since the slider is coded in JavaScript, I am not sure how to control the scroll position. I would ...