I am using FileSaver.js where I need to convert HTML table to xls using AngularJS.
Works fine with all browser but issue with iOS device.
Any alternate solution or any other plugin that can be used?
The following Gist at Github shows you how to export an HTML table to Microsoft Excel.
myApp.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;
}
};
})
.controller('MyCtrl',function(Excel,$timeout){
$scope.exportToExcel=function(tableId){ // ex: '#my-table'
$scope.exportHref=Excel.tableToExcel(tableId,'sheet name');
$timeout(function(){location.href=$scope.fileData.exportHref;},100); // trigger download
}
});
And then call it for example like this:
<button class="btn btn-link" ng-click="exportToExcel('#table1')">
<span class="glyphicon glyphicon-share"></span> Export to Excel
</button>
Related
require:I need to download files from server in mobile.
question:
In pc:
<a href="file.url">
click me to download
</a>
and
<a #click="func"></a>
<script>
function func(){
var myFrame= document.createElement(“iframe”);
myFrame.src = “url”;
myFrame.style.display = “none”;
document.body.appendChild(myFrame);
}
</script>
botn works well,but it can't work well in mobile,how can I realize it?
I want to export data in my html table to an excel sheet using angularjs on abutton click. I tried a code, but in vain.i m getting the button click event triggered though but nothing else seems to happen
<table class="table table-bordered table-condensed table-hover table-striped" id="tableId">
<tr ng-repeat="mas in vm1 | orderBy:orderByField:reverseSort">
<td>{{::mas.contractNumber}} </td>
<td>{{::mas.planNumber}} </td>
<td>{{::mas.businessErrorMsg }} </td>
<td>{{::mas.systemErrorMsg}} </td>
</tr>
<button class="btn btn-link" ng-click="exportToExcel('#tableId')">
<span class="glyphicon glyphicon-share"></span>Export to Excel
</button>
//controller code
app.controller("ErrorDetailController", [
"$scope", "$location", "$routeParams", "messageService", "errorService", "repositoryService", , "sharedPageService",
function ($scope, $location, $routeParams, messageService, errorService, repositoryService,sharedPageService, **Excel, $timeout**) {
$scope.exportToExcel = function (tableId) { // ex: '#my-table'
debugger;
var exportHref = Excel.tableToExcel(tableId, 'sheet name');
$timeout(function () { location.href = exportHref; }, 100); // trigger download
}
}
]);
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;
}
};
})
Use :
<body>{table}</body>
instead of :
<body><table>{table}</table></body> in template variable.
You can use the ng-table-to-csv module to export HTML tables into CSV files (that can be opened in Excel).
As given on the README of that repo, here is the usage:
Getting Started / Usage
Install module via bower (or download the files from the dist folder
in the repo):
shell bower install ng-table-to-csv --save
Add a reference to dist/ng-table-to-csv.js into your HTML pages.
Add ngTableToCsv as a dependency to your module:
js angular.module('your_app', ['ngTableToCsv']);
Add export-csv attribute directive on the table to define a new
csv object on the scope with generate() and link() functions on
them.
Options:
- Use the separator attribute to change the default comma separator into something else (like semicolon).
- Use the export-csv-ignore attribute to set the selector that will be used for prevent tr/th/td to be stringified.
To create an Export button from an anchro tag, use the generate()
and link() functions mentioned above from ng-click and ng-href
attributes of an anchor tag.
See below:
html
<a class="btn" title="Export Table" ng-click='csv.generate()' ng-href="{{ csv.link() }}"
download="myTable.csv">
<i class="glyphicon glyphicon-new-window"></i> Export
</a>
<table class="table table-bordered" export-csv="csv" separator=";">
<!-- table contents -->
</table>
I am currently trying to develop a small tool that changes certain elements in an html file - one of those elements is a "bulletproof CSS button" for email as seen in the following page:
Campaign Monitor
The commented block of code looks like this:
<!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="http://google.com" style="height:30px;v-text-anchor:middle;width:170px;" arcsize="9%" stroke="f" fillcolor="#34adb2"><w:anchorlock><center></center></w:anchorlock></v:roundrect><![endif]-->
Now, as you can see, such code contains an mso comment, I was wondering if there is any way to use Javascript to target this element and change the href attribute, I have tried alerting the commented elements on the page using the following code:
$(function() {
$("body").contents().filter(function(){
return this.nodeType == 8;
}).each(function(i, e){
alert(e.nodeValue);
});
});
So far this only alerts the native HTML comments and not the specific mso comment I'd like to change.
Is there any other way to target this comment? Any help will be greatly appreciated!
I wrote some simple codes in various scenarios, you can use one of them base witch you want. ;)
I tested them by IE 11
In these examples we have some HREFs value:
www.mysite. com << this is the default value
www.example.com << this is our new value
Now codes:
HTML
This:
<div id="mybtn">
Show me the button!
<!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="http://http://www.mySite. com" style="height:40px;v-text-anchor:middle;width:200px;" arcsize="10%" strokecolor="#1e3650" fill="t">
<v:fill type="tile" src="http://i.imgur.com/0xPEf.gif" color="#556270" />
<w:anchorlock/>
<center style="color:#ffffff;font-family:sans-serif;font-size:13px;font-weight:bold;">Show me the button!</center>
</v:roundrect><![endif]-->
</div>
Or this:
<div id="mybtn">
<!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="http://http://www.mySite. com" style="height:40px;v-text-anchor:middle;width:200px;" arcsize="10%" strokecolor="#1e3650" fill="t">
<v:fill type="tile" src="http://i.imgur.com/0xPEf.gif" color="#556270" />
<w:anchorlock/>
<center style="color:#ffffff;font-family:sans-serif;font-size:13px;font-weight:bold;">Show me the button!</center>
</v:roundrect><![endif]-->
Show me the button!
</div>
The codes state before running any scripts:
.
.
A) Javascript (just Changing HREF property of v:roundrect tag)
$("div#mybtn").contents().filter(
function(){
return this.nodeType == 8;
}).each(function(i,e){
if(i==0)
{
$(this)[0].data = replaceHrefWithNew($(this)[0].data,"http://www.example.com");
console.log($(this));
}
});
function replaceHrefWithNew(myMso,newHrefValue)
{
var newMso=myMso;
var indexOfStartHref=myMso.indexOf("href")+6;
if(indexOfStartHref>=6)
{
var indexOfEndHref=myMso.indexOf("\"",indexOfStartHref);
var part1=myMso.substring(0,indexOfStartHref);
var part2=myMso.substring(indexOfStartHref,indexOfEndHref);
var part3=myMso.substring(indexOfEndHref);
newMso= part1 + newHrefValue + part3;
}
alert(newMso);
return newMso;
}
Result after run Script A
.
.
B) Javascript (Changing HREF property of v:roundrect tag & A tag together)
$(document).ready(function(){
var webAddress="http://www.example.com";
$("div#mybtn").contents().filter(
function(){
return this.nodeType == 8;
}).each(function(i,e){
if(i==0)
{
$(this)[0].data = replaceHrefWithNew($(this)[0].data,webAddress);
console.log($(this));
}
});
$("div#mybtn").find('a:first').prop("href",webAddress);
});
function replaceHrefWithNew(myMso,newHrefValue)
{
var newMso=myMso;
var indexOfStartHref=myMso.indexOf("href")+6;
if(indexOfStartHref>=6)
{
var indexOfEndHref=myMso.indexOf("\"",indexOfStartHref);
var part1=myMso.substring(0,indexOfStartHref);
var part2=myMso.substring(indexOfStartHref,indexOfEndHref);
var part3=myMso.substring(indexOfEndHref);
newMso= part1 + newHrefValue + part3;
}
alert(newMso);
return newMso;
}
Result after run Script B
.
.
C) Javascript (Just changing HREF property A tag)
In this case you can simply use below jquery code:
$(document).ready(function(){
var webAddress="http://www.example.com";
$("div#mybtn").find('a:first').prop("href",webAddress);
});
Result after run Script C
I need to put a certain table into an Excel table.
I am using the solution to this question:
HTML Table to Excel Javascript
I left the JS unchanged, like this:
<script type="text/javascript">
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) table = document.getElementById(table)
var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
document.getElementById("dlink").href = uri + base64(format(template, ctx));
document.getElementById("dlink").download = filename;
document.getElementById("dlink").click();
}
})()
</script>
This is the HTML I use to trigger the download:
The anchor:
<a id="dlink" href="#testTable" style="display:none;"></a>
The button:
<input type="button" onclick="tableToExcel('testTable', 'testTable', 'myExport.xls')" value="Export to Excel">
The table attributes:
<table data-name="testTable" id="testTable" summary="All members" rules="groups" frame="hsides" border="2">
Once I click the button, it opens Excel and gives me the following error:
'C:\users\username\AppData\Local\Temp\myExport.xls' could not be found. Check the spelling (insert rest of microsoft BLA here)
Any help appreciated!
Just found out the following:
IE == NOT EVEN WORKING
Chrome == Gives me file, but leaves some fields filled with the value 'тВм0'.
FireFox == 'C:\users\username\AppData\Local\Temp\myExport.xls' could not be found. Check the spelling (insert rest of microsoft BLA here)
Since this topic received 0 feedback i found this thread after searching a while.
html to excel export with .xls extension in javascript or php
This gave me the solution. I hope it helps others too.
How do I change the name of file while exporting data to Excel?
<div id="example" class="k-content">
<button type="button"id="btnExport">Export to csv!</button>
<div id="grid"></div>
</div>
<script>
$("#btnExport").click(function (e) {
var result = "data:application/vnd.ms-excel,";
window.open(result);
e.preventDefault();
});
</script>
When I click the export button I am getting as download.xls. Is it possible to set the file name as data.xls? Can any one explain me where I need to configure that?
here is an example which demonstrates Export HTML Table to Excel With Custom File Name: http://www.kubilayerdogan.net/javascript-export-html-table-to-excel-with-custom-file-name/
Not only for excel, in addition, for many kind of format can useable.
var element = document.createElement('a');
element.setAttribute('href', 'data:application/vnd.ms-excel,' + encodeURIComponent(htmlTable));
element.setAttribute('download', fileName);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server
I had the same issue, and since the new format (maybe not supported by every browser) <a download=""></a> the following worked fine for me. This use directly HTML/Javascript without the PHP server part, because using a submit form is too heavy for big data tables.
changing <button> to <a>
no more window.open()
using the basic <a> behavior (so, no more e.preventDefault()) but changing href to data:blabla and adding download="filename" :
<div id="example" class="k-content">
<a href="#" id="btnExport" >Export to csv!</a>
<div id="grid"></div>
</div>
<script>
$("#btnExport").click(function (e) {
var result = "data:application/vnd.ms-excel,";
this.href = result;
this.download = "my-custom-filename.xls";
return true;
});
</script>
You can't do this with client-side JavaScript, you need to set the response header...
.NET
Response.AddHeader("Content-Disposition", "inline;filename=filename.xls")
Or PHP
$filename = 'somehting.xls';
header('Content-Disposition: attachment; filename="'.$filename.'"');
Response.AddHeader "Content-Disposition", "attachment; filename=C:\YOURFILENAME.xls;"
var a = document.createElement('a');
//getting data from our div that contains the HTML table
var data_type = 'data:application/vnd.ms-excel';
a.href = data_type + ', ' + encodeURIComponent(tab_text);
//setting the file name
a.download = 'SupervisorReport.xls';
//triggering the function
a.click();
//just in case, prevent default behaviour
e.preventDefault();
return (a);