What are the best ways to prepare an Excel document for exportation?

I am looking for a way to control the layout of a file before exporting it. For example, I need to fix the width of columns, set the title color, add borders to tables, highlight specific rows, or enable word wrapping programmatically before exporting. My project is built using AngularJS. Can anyone suggest a library that supports these functionalities? Here is an example image of what I am trying to achieve: Picture of Excel File

Unfortunately, when I tried using alasql library to set column widths, I encountered this bug. Bug Screenshot

Does anyone have any suggestions on how to fix this issue?

Answer №1

 app.factory('Excel', function ($window) {
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 {
    tableToExcel: function (tableId, worksheetName) {
        var table = $(tableId),
            ctx = { worksheet: worksheetName, table: table.html() },
            href = uri + base64(format(template, ctx));
        return href;
    }
};
})

execute the following function

  $scope.exportToExcel = function (tableId) { // ex: '#my-table'          
    var exportHref = Excel.tableToExcel(tableId, 'sheetname');
    $timeout(function () { location.href = exportHref; }, 100); // initiate download
}

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

What is the best way to choose the initial p tag from an HTML document encoded as a string?

When retrieving data from a headless CMS, the content is often returned as a string format like this: <div> <p>1st p tag</p> <p>2nd p tag</p> </div> To target and select the first paragraph tag (p), you can extract ...

The use of jQuery for fetching posts via ajax can lead to a crash in the browser

I have a social media platform where I implemented jQuery on the main feed page. The jQuery is set up so that as users scroll down, the next batch of posts is fetched using ajax and added to the DOM. However, after a few ajax requests, the browser slows do ...

JavaScript - Capture the Values of Input Fields Upon Enter Key Press

Here's the input I have: <input class="form-control" id="unique-ar-array" type="text" name="unique-ar-array" value="" placeholder="Enter a keyword and press return to add items to the array"> And this is my JavaScript code: var uniqueRowsArr ...

Is there a way to determine if a parent of my HTML element possesses a CSS class?

Looking at this HTML code snippet - <div id="parent" class="foo"> <div id="child"> </div> </div> Is there a way to create a test to verify if the child element is utilizing the foo class? I attempted: element .children("#chi ...

Assess the performance of an input with jest

I have created a new component that is a Checkbox with React Hooks: import React, {useState} from 'react'; const Checkbox = () => { const [checked, setChecked] = useState(false); return ( <div> <input o ...

Storing Data in an Array Using MongoDB's $push Method Depending on a Variable's Value

I'm attempting to add an item to my MongoDB record in Node (using MongoJS) by using the $push method. Here is an example of how it's done: exports.saveToUser = function (req, res) { console.log("IN"); var user = req.params.user; var ...

A Guide to Executing Asynchronous Function Calls in a For Loop using JavaScript

Experiencing issues with asynchronous calls within a for loop in my code. The loop progresses before the async call is completed, causing unexpected behavior. As someone new to this language, I'm trying to understand callbacks and other related concep ...

The tooltip in Amcharts malfunctions when incorporating the DurationAxis

I've been grappling with getting tooltips to work in amCharts4 when using a DurationAxis(). It seems like there might be a bug, as the tooltips sometimes get stuck in the top left corner. Here's an example: https://jsfiddle.net/jamiegau/fpye3bkv ...

Sending an AJAX Post Request Using a Raw HTTP Call in JavaScript

I need assistance with sending a POST request using pure JavaScript. Is it possible to send the above HTTP request as a variable and collect the response? Alternatively, is there a more effective method for sending this POST request in JavaScript? ...

performing an AJAX call utilizing both a file and post data

I'm reaching out for help because I'm having trouble sending an ajax request with a data file and two posts included Here is the code snippet: $('#image--1').change(function (e) { e.preventDefault(); var img = new FormData(); ...

Warning: Axios is sending duplicate CSRF-Tokens, resulting in a CSRF-Token mismatch

I am facing an issue with my Laravel/Vue with Sanctum setup. The problem is simple: When I send a token request and log in the user, the server responds with a new token. However, Axios is adding this new token along with an additional token that is alway ...

Searching in AngularJs while ignoring diacritics

I'm thinking of creating a word list with plenty of diacritics and accents. For example, instead of typing Róse as Rose, I want to have Róse displayed in the results. Initially, I searched for a solution on StackOverflow where the issue was somewhat ...

Mastering JavaScript without the use of the `new` keyword: Unleashing the Power of the Good Parts

In his book, "JavaScript: The Good Parts," Crockford emphasizes the importance of giving constructor functions names with an initial capital letter (e.g., Point) and using function names with initial capital letters only with constructor functions, while e ...

"Using Django REST framework, create a class-based view that extracts dataObj IDs from DataTables

I've been working with datatables to select and delete rows in my project. While I can successfully select rows and retrieve their IDs using the button #countbuttonids, I'm facing issues when trying to delete the objects with the specified IDs in ...

Filtering in AngularJS can be performed by checking if a value in a specific key of one array is also present as a value in a specific

This query was originally posted on this thread I am looking to implement a filter that will display the values of colors.name only if they also exist in cars.color $scope.colors = [{"name":"blue","count":2}, {"name":"red","count":12}, ...

styled(MyComponent) will display MyComponent as is, without any extra styling applied

Two React components I have are utilizing styled-components. The first one named Div simply renders a basic div: import React from "react"; import styled from "styled-components"; export default function Div(props) { return <StyledDiv>{props.chil ...

Importing Vue components dynamically from a specific subdirectory

I'm having trouble importing all files with the .vue extension from a specific subfolder into another component. I am aware of the concept of Automatically Registering Base Components Globally, but it doesn't seem to be applicable in this case. ...

sending arguments to the event handler function

It seems like I may be overlooking some basic concepts of JavaScript events. Could someone kindly explain why these two calls are returning different results? // 1 $(window).on('load', function(){ spiderLoad(); }); and // 2 $(window).on(& ...

Ensure that every div on the page matches the height of the initial div

I have implemented the following code: //Adjust Div Size $(document).ready(function(){ adjustSize(); }); window.onresize = function(event) { adjustSize(); } function adjustSize() { vpw = $(window).width(); vph = $(window).height(); ...

Real-Time Updating of Countdown Timer using JavaScript every passing second

I am currently working on a PHP script that displays the countdown until an event. The time remaining is shown in a format like this: 23h 15m 4s Below is the PHP code I am using: $now = new DateTime(); $future_date = new DateTime($res['post_ ...