GithubHelp home page GithubHelp logo

jquery-table2excel's Introduction

#Credit for the core table export code concept goes to insin (met on Freenode in #javascript) and core code inspired from https://gist.github.com/insin/1031969

FIRST!!

Thanks for your interest. I haven't been able to maintain this and found the following project which looks well ahead of this one, so you may want to consider it first: TableExport

DISCLAIMER

This plugin is a hack on a hack. The .xls extension is the only way [some versions] of excel will even open it, and you will get a warning about the contents which can be ignored. The plugin was developed against Chrome and other have contributed code that should allow it to work in Firefox and Safari, but inconsistently since it's a hack that's not well supported anywhere but Chrome. I would not use this in public production personally and it was developed for an Intranet application where users are on Chrome and had known versions of Excel installed and the users were educated about the warning. These users also save-as in Excel so that when the files are distributed, the end-users don't get the warning message.

Install - Bower

Install bower globally

npm install -g bower

Install jquery-table2excel and dependencies

bower install jquery-table2excel --save

Include jquery and table2excel in your page

<script src="bower_components\jquery\dist\jquery.min.js"></script>
<script src="bower_components\jquery-table2excel\dist\jquery.table2excel.min.js"></script>

Install - Legacy

Include jQuery and table2excel plugin:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js"></script>

Using the plugin

$("#yourHtmTable").table2excel({
    exclude: ".excludeThisClass",
    name: "Worksheet Name",
    filename: "SomeFile.xls", // do include extension
    preserveColors: false // set to true if you want background colors and font colors preserved
});

Contains a simple HTML file to demonstrate your plugin.

This is where the generated files are stored once Grunt runs.

This file is for unifying the coding style for different editors and IDEs.

Check editorconfig.org if you haven't heard about this project yet.

List of rules used by JSHint to detect errors and potential problems in JavaScript.

Check jshint.com if you haven't heard about this project yet.

Definitions for continous integration using Travis.

Check travis-ci.org if you haven't heard about this project yet.

Package manifest file used to publish plugins in jQuery Plugin Registry.

Check this Package Manifest Guide for more details.

Contains all automated tasks using Grunt.

Check gruntjs.com if you haven't heard about this project yet.

Specify all dependencies loaded via Node.JS.

Check NPM for more details.

Contributing

Check CONTRIBUTING.md

History

Check Release list.

License

MIT License

jquery-table2excel's People

Contributors

ashleylv avatar dangranlund avatar dependabot[bot] avatar fellowsome avatar gentcys avatar gioce90 avatar heinst avatar jorix avatar kenttanl avatar killer2005 avatar macieljr avatar neal-liu avatar own3mall avatar rainabba avatar seandevoy avatar someguy0005 avatar unconditional avatar wangyang135 avatar zach14c avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-table2excel's Issues

Issue with xlsx - xls works

I've found that outputting the file as a xlsx creates a corrupt file / not recognised properly by Excel or OpenOffice / LibreOffice.

Changing the output to xls works fine, and it can be opened correctly.

You might want to allow people to specify the extensions when passing 'filename', as they might find xlsx doesn't always work.

Open error in excel

Hi,
i download the latest versión of js file, after read all issues, when i save the file, and then i try to open, the Excel file return an error about the type of the file or the extensión.
I don't know what more to do.
Thanks

IE + XLSX Format support

It doesn't work in IE10 and lower versions. Also there should be a way to download file in xlsx format.

Only Firefox

Hello,

I just tested your great script on Firefox, IE and Chrome.

  • Firefox : Ok !
  • IE : when I open the .xls file, there is only {table0} on the first cell.
    EDIT : it works with IE when patch the #46 issue ;)
  • Chrome : "Network error" when trying to download the file

PS : sorry if you don't understand, I'm french ;)

Adding HTML content to head

Hello,
My customer wants some headings to excel. For example:

<div id="table2excel">
<h1>Heading</h1>
<table>
...
</table>
</div>

I think these support not good for jquery-table2excel. Because its table to excel. But, how can I do that?

How to change extension

I am using Office 2016 and it doesnt seem to open the .xlsx default extension.
But when i manually change the extension to .xls it opens with warning.

Is there any way to force the extension to be .xls?

I did note the readme but couldnt find a way to force the extension default;
..The .xls extension is the only way [some versions] of excel will even open it, and you will get a warning about the contents which can be ignored....

Datatables problem

Hello i've integrated the plugin on a datatables table.. but the bootstrap put the data from table on different pages, when i try to export using your plugin it extracts only the first page
untitled

use ie download file display function (predicate)

hi,
I use ie11 download same xls file , but when i open , some function display on my table.

function (predicate) { if (this == null) { throw new TypeError('Array.prototype.find called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return value; } } return undefined; }
function (predicate) { if (this === null) { throw new TypeError('Array.prototype.findIndex called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return i; } } return -1; }
function (searchElement /*, fromIndex*/) { var O = Object(this); var len = parseInt(O.length) || 0; if (len === 0) { return false; } var n = parseInt(arguments[1]) || 0; var k; if (n >= 0) { k = n; } else { k = len + n; if (k < 0) { k = 0; } } var currentElement; while (k < len) { currentElement = O[k]; if (searchElement === currentElement || searchElement !== searchElement && currentElement !== currentElement) { return true; } k++; } return false; }

Plugin restarts the page after execution

I have used a button which calls the plugin ONCLICK. But when I click the button.. the download pop-up appears, but the page restarts. Can you help me?

Thanks in advance!
Madhura ganesh K

Content coming as {table0}

Hi Guys,

After referring the latest Js file I am not able to export any of my content. Exported content is coming as {table0} in excel sheet. Could you please let me know the correct JS reference ?

Regards,
Rama

Not working on various browsers

This may be related to this issue: #15
I am running OS X El Capitan Version 10.11.2.

In FirefoxDeveloperEdition v45.0a2 (2015-12-20), the table2excel function won't even fire. Nothing happens. I don't even see an entry in the logs. I get the same behavior on regular Firefox (v.33.0.3).

In Chrome v47.0.2526.106 (64-bit), it will generate a file and prompt me for where to save the file, but when I try to open the file in Excel I get:
"Excel cannot open this file. The file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."

In Safari v.9.0.2 (11601.3.9), the file will be generated and immediately drop into my downloads folder, but it won't have a file extension so I can't open it with Excel out of the box. If I manually rename the file with the ".xls" extension, I can view it in Excel just fine.

support for numbers with a leading "0"

hi rain. is there any way to augment the code to add a flag to support columns that contain numbers, similar to the flag you use to exclude columns?

when you export a column with numbers that have a leading zero, excel trims the zero out of the code entirely when it opens. if we could augment those columns to add a few characters it would work correctly (where 000123 will show 123 in excel, ="000123" will show 000123 in excel).

Double thead with rowspan

Hi, can anybody help with this issue:

thead
    tr
      th{rowspan=2}
      th{rowspan=2}
      th{colspan=3}
      th{rowspan=2}
    tr
      th
      th
      th

This code causes double thead in file.

Multiple Tables

I have different tables on the same page.
How can I make both the tables exported into the same excel file on the click of a single button?
I also have another constraint. The page is dynamic so I wouldn't know how many tables would appear on my page.

Not working in Safari and Mobile Browsers

This plugins works fine in Chrome, IE and firefox on my desktop, but doesn't work in Safari and Android default mobile browser. By doesn't work, I mean, nothing happens on clicking Export button and no error in console as well.

Add heading

I need to add heading to the table, as a parameter , currently achieved using
fullTemplate += e.template.mid;
fullTemplate += "Report Heading";

But need ths to be dynamic with html TAGS.

Please update the code in the /dist folder!

The code in the "src" and in the "dist" folder are not identical, for example the code in the "dist" folder does not work with firefox, while the one in the "src" folder has a fix for it. (see 2005265)
So please update the code in the "dist" folder!

EXCLUDE doesn't need to be whole row Feature (with simple code change)

FYI: I love this add-in!

Currently, the "exclude" filter only ignores complete s (rows) with the matching class on them. I had a need to export a table and NOT export "controls" like Buttons and dropbox items into the spreadsheet.

With a very simple change to the code, individual s can have there content ignored. Code does not display well here, but the idea is simple. Step through the item's s. If the contains something with the exclude class, send an empty , otherwise send its contents. There is probably a cleaner way to do this, jQuery tips will be welcomed.

I changed:
// get contents of table except for exclude $(e.element).each( function(i,o) { var tempRows = ""; $(o).find("tr").not(e.settings.exclude).each(function (i,o) { tempRows += "<tr>" + $(o).html() + "</tr>"; }); e.tableRows.push(tempRows); });

to:
`
// get contents of table except for exclude
$(e.element).each( function(i,o) {
var tempRows = "";
$(o).find("tr").not(e.settings.exclude).each(function (i,p) {
tempRows += "";
$(p).find("td").not(e.settings.exclude).each(function (i,q) {
var flag = $(q).find(e.settings.exclude) // does this have an exclude item
if(flag.length >= 1) {
tempRows += " " // exclude it!!
} else {
tempRows += "" + $(q).html() + ""
}
})

                tempRows += "</tr>";
            });
            e.tableRows.push(tempRows);
        });

`
Now I my "controls" are excluded from the spreadsheet.

Hope that helps someone out.
Sean

exclude_img: true — not working

i use t2e with this settings:

    $("#restaurant_stat").table2excel({
        exclude: ".noExl",
        name: "SmartReserve",
        filename: xlsFilename,
        fileext: ".xls",
        exclude_img: true,
        exclude_links: true,
        exclude_inputs: true
    });

but image boxes are included:

screen shot 2016-06-29 at 12 14 17

whats wrong?

Saving as XLSX doesn't open in Office 365, XLS does

This evening I gave this plug-in a run, thank you for your work. What I noticed was a few things - first you are suggesting for people to use the dist/ files and I assume this is after a grunt build? Without the grunt build I get an error about "no MSIE". See screenshot:
nomsie

Finally I would like to provide you the two examples for my bug report. What I notice is that if I save the files as XLS they will open (with warning) in the latest version of Office. If I use the out of the box extension - they will not open at all and Excel just claims that are incorrectly formatted.

I will attach two examples of the output (which are the same - only difference is file extension) for your review.

XLSX
export-report.xlsx

(Sorry it looks like I can not upload an XLS to github, only XLSX - just make a copy and change the extension)

Thank you again - this plug-in has saved me some time!

Exporting 2 decimal places

The plugin while exporting a percentage value with one decimal place automatically suffixes a 0, thus making it 2 decimal places even though its not there in the html.
ie if table shows: 94.1% the exported table shows : 94.10%

demo folder

i'm clone repo and open /demo folder
and get err in console in chrome
jquery.table2excel.js:50 Uncaught ReferenceError: p is not defined

Excel doesn't download in Firefox

The converted excel file does not download in firefox because a.click() (in jquery.table2excel.js) is not working.
Firefox version: 35.0.1 (for Ubuntu)

file_get_contents(); if needed. (See explanation below)

After the table is succesfully converted to excel, I upload that excel file to server and using PHPExcel plugin i try to view this excel file's content, but an errors shows up. It says your file is not readable. Is there any way to make our .xls files readable (creating proper* excel files via table2excel) upon converting table to excel?
Thanks in advance.

multiple sheets

i want to download a single excel worksheet with multiple sheets. any solutions?

thead is lost..

Hi I'm starting to use your library, but when exporting, the thead did not appear.

I would be delighted if you could guide me a bit ..

Cheers..

My code is this.

$("#exportExcel").click(function(){

      $('<table>')
         .append(
              //$("#example thead tr").clone().prependTo($("#example thead"))
            $("#example").DataTable().$('tr').clone()
         )
         .table2excel({
            name: "Worksheet Name",
            filename: "SomeFile" //do not include extension
         });

});

The commented line, brings me only thead, and the other, if it brings me all content.

Sorry for my bad english, im mexican.
Thank you.

code segment to work for IE

;(function ( $, window, document, undefined ) {
var pluginName = "table2excel",

defaults = {
    exclude: ".noExl",
            name: "Table2Excel"
};

// The actual plugin constructor
function Plugin ( element, options ) {
        this.element = element;
        // jQuery has an extend method which merges the contents of two or
        // more objects, storing the result in the first object. The first object
        // is generally empty as we don't want to alter the default options for
        // future instances of the plugin
        // 
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
}

Plugin.prototype = {
    init: function () {
        var e = this;

        e.template = {
            head: "<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>",
            sheet: {
                head: "<x:ExcelWorksheet><x:Name>",
                tail: "</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>"
            },
            mid: "</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>",
            table: {
                head: "<table>",
                tail: "</table>"
            },
            foot: "</body></html>"
        };

        e.tableRows = [];

        // get contents of table except for exclude
        $(e.element).each( function(i,o) {
            var tempRows = "";
            $(o).find("tr").not(e.settings.exclude).each(function (i,o) {
                tempRows += "<tr>" + $(o).html() + "</tr>";
            });
            e.tableRows.push(tempRows);
        });


        e.tableToExcel(e.tableRows, e.settings.name);
    },

    tableToExcel: function (table, name) {
        var e = this, fullTemplate="", i, link, a;

        e.uri = "data:application/vnd.ms-excel;base64,";
        e.base64 = function (s) {
            return window.btoa(unescape(encodeURIComponent(s)));
        };
        e.format = function (s, c) {
            return s.replace(/{(\w+)}/g, function (m, p) {
                return c[p];
            });
        };
        e.ctx = {
            worksheet: name || "Worksheet",
            table: table
        };

        fullTemplate= e.template.head;

        if ( $.isArray(table) ) {
            for (i in table) {
                //fullTemplate += e.template.sheet.head + "{worksheet" + i + "}" + e.template.sheet.tail;
                fullTemplate += e.template.sheet.head + "Table" + i + "" + e.template.sheet.tail;
            }
        }

        fullTemplate += e.template.mid;

        if ( $.isArray(table) ) {
            for (i in table) {
                fullTemplate += e.template.table.head + "{table" + i + "}" + e.template.table.tail;
            }
        }

        fullTemplate += e.template.foot;

        for (i in table) {
            e.ctx["table" + i] = table[i];
        }
        delete e.ctx.table;


        if (typeof msie !== "undefined" && msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
        {
            if (typeof Blob !== "undefined") {
                //use blobs if we can
        ieFullTemplate = e.format(fullTemplate, e.ctx);
                ieFullTemplate = [ieFullTemplate];
                //convert to array
                var blob1 = new Blob(ieFullTemplate, { type: "text/html" });
                window.navigator.msSaveBlob(blob1, getFileName(e.settings) );
            } else {alert("in else");
                //otherwise use the iframe and save
                //requires a blank iframe on page called txtArea1
                txtArea1.document.open("text/html", "replace");
                txtArea1.document.write(fullTemplate);
                txtArea1.document.close();
                txtArea1.focus();
                sa = txtArea1.document.execCommand("SaveAs", true, getFileName(e.settings) );
            }

        } else {
            link = e.uri + e.base64(e.format(fullTemplate, e.ctx));
            a = document.createElement("a");
            a.download = getFileName(e.settings);
            a.href = link;

            document.body.appendChild(a);

            a.click();

            document.body.removeChild(a);
        }

        return true;

    }
};

function getFileName(settings) {
    return ( settings.filename ? settings.filename : "table2excel") + ".xls";
}

$.fn[ pluginName ] = function ( options ) {
    var e = this;
        e.each(function() {
                if ( !$.data( e, "plugin_" + pluginName ) ) {
                        $.data( e, "plugin_" + pluginName, new Plugin( this, options ) );
                }
        });

        // chain jQuery functions
        return e;
};

})( jQuery, window, document );

Doesn't download file in IE10, files created with xlsx extension won't open in Outlook 2010.

Hello! I seem to running into some issues. First, we use IE10 where I work and it's probably going to stay that way for awhile, but the file doesn't download at all in IE10. I added this condition where you check for the userAgent string for IE11: !!navigator.userAgent.match(/Trident.*6/), so that if statement checks for IE11 or 10, and it downloads the file now.

The second problem is any file downloaded with the .xlsx extension won't open in Excel for some reason. If I rename the file to have an extension of .xls, they will open.

This plugin isn't working for IE 9

the brower alert error msg:SCRIPT5009: “txtArea1” undifined
jquery.table2excel.js, 行135 字符21

what is the “txtArea1“?

giving a userdefined name to the file

Great plugin bro. Is it possible to give a default user defined file name . Right now it directly shows 'download' as the name of the file.One more thing what in the case of two tables.How to export both the tables in one file ? I think giving them a common class and then calling with class instead of id won't work , right ?

Image doesn't appear in Excel file

Hi, i use this amazing library in my Symfony project. All data is reported excepted images. Here is what i do:

<table class="table table2excel">
            <thead>
            <tr>
                <th>
                    <img src="{{ asset('img/button_cancel.png') }}" alt="btn">
                </th>
                <th>Nom</th>
                <th>Prenom</th>
                <th>Age</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td>1</td>
                <td>{{ name }}</td>
                <td>Omar</td>
                <td>40</td>
            </tr>
            <tr>
                <td>1</td>
                <td>{{ name }}</td>
                <td>Iba</td>
                <td>24</td>
            </tr>
            </tbody>
            <tfoot>
            <tr>
                <td colspan="4">
                    <a href="#" class="exportBtn"><img src="{{ asset('img/icons/excel48.png') }}"></a>
                </td>
            </tr>
            </tfoot>
        </table>

And the JS code :

$(function () {
    $(".exportBtn").click(function() {
        var current = new Date();
        $(".table2excel").table2excel({
            // Exclude CSS class
            exclude: ".noExl",
            exclude_img: false,
            file_ext: ".xls",
            name: "test",
            filename: "export" + current.getSeconds()
            // Do not include extension
        });
    });
});

The button cancel image doesn't appear.

not working with Internet Explorer

On Internet-Explorer 9 and 10 an error occured.
And with Internet-Explorer-11 the result is only one cell with the value "{table0}"

need help ....

thank you !

Update demo

Please update demo, show how to work with multiple tables. It's not working for me.

Exlude Column?

Hello rainabba,
It's great simple plugin. But is there any option to exclude a column base on 'colgroup' or 'th' ?

UTF-8 Problem

Hello,
I have some turkish characters in HTML table. When I downloaded .xls table2excel file. Turkish characters looking bad/broken

thanks! having some problems with IE

hi rain. great plugin its working very well for me, however i cant seem to get this working in IE. im testing in IE version 11 and nothing happens when i click my export button. it works perfectly in chrome/firefox... i see someone posted an issue about using IE and about setting the file extension but i dont see that there was a clear resolution there. for your reference my table is named table2excel and the code im using is:
$("#Export").click(function () {
$("#table2excel").table2excel({
// exclude CSS class
exclude: ".filtered",
name: "ProductReport"
});
});

strange message about file format

im install plugin into my app with options:

    $("#restaurant_stat").table2excel({
        exclude: ".noExl",
        name: "SmartReserve",
        filename: xlsFilename,
        fileext: ".xls",
        exclude_img: false,
        exclude_links: false,
        exclude_inputs: false
    });

my table are converted, but on the run i have Strange message:

screen shot 2016-06-21 at 20 10 14

help e please

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.