Coder Social home page Coder Social logo

buttons's Introduction

Buttons

The Buttons extension for DataTables provides a common set of options, API methods and styling to display buttons on a page that will interact with a DataTable. Modules are also provided for data export, printing and column visibility control.

Installation

To use Buttons the primary way to obtain the software is to use the DataTables downloader. You can also include the individual files from the DataTables CDN. See the documentation for full details.

NPM and Bower

If you prefer to use a package manager such as NPM or Bower, distribution repositories are available with software built from this repository under the name datatables.net-buttons. Styling packages for Bootstrap, Foundation and other styling libraries are also available by adding a suffix to the package name.

Please see the DataTables NPM and Bower installation pages for further information. The DataTables installation manual also has details on how to use package managers with DataTables.

Basic usage

Buttons is initialised using the buttons option in the DataTables constructor, giving an array of the buttons that should be shown. Further options can be specified using this option as an object - see the documentation for details. For example:

$(document).ready( function () {
    $('#example').DataTable( {
    	buttons: [ 'csv', 'excel', 'pdf', 'print' ]
    } );
} );

Documentation / support

GitHub

If you fancy getting involved with the development of Buttons and help make it better, please refer to its GitHub repo

buttons's People

Contributors

aadash avatar alesak avatar allanjard avatar chulkilee avatar colin0117 avatar diegonogueira avatar elizabethcoleman avatar fabienlucini avatar fdaugan avatar gillesvermeulen avatar hannesoberreiter avatar hiwanz avatar jamstah avatar joe-meyer avatar johndavissds avatar jpobley avatar jybleau avatar kueblc avatar mscdex avatar muellermatthew avatar paulomoreno avatar petermorlion avatar redjokinginn avatar sandydatatables avatar tfermm avatar tharglet avatar thomasbuckle-uk avatar woodham avatar worthy7 avatar wridgeu 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

buttons's Issues

JS crash when loading dynamic data integers

Datatables buttons csv export crashes when loading an integer that is provided with Javascript sourced data:

var dataSet = [
    [ "Tiger Nixon", "System Architect", "Edinburgh", 5421, "2011/04/25", "$320,800" ]
];

$(document).ready(function() {
    $('#example').DataTable( {
        data: dataSet,
        buttons: [ 'csv' ], 
        columns: [
            { title: "Name" },
            { title: "Position" },
            { title: "Office" },
            { title: "Extn." },
            { title: "Start date" },
            { title: "Salary" }
        ]
    } );
} );

issue to convert a table with numbers into csv file

Hello my use case is here (from your site) :

    var mytable=$('#example').DataTable( {
        "data": [
        {
            "name":       "Tiger Nixon",
            "position":   "System Architect",
            "salary":     "$3,120",
            "start_date": "2011/04/25",
            "office":     "Edinburgh",
            "extn":       5421
        },
        {
            "name": "Garrett Winters",
            "position": "Director",
            "salary": "5300",
            "start_date": "2011/07/25",
            "office": "Edinburgh",
            "extn": "8422"
        },
        // ...
    ],
        "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "salary" },
            { "data": "extn" },
            { "data": "start_date" },
            { "data": "salary" }
        ],
        buttons: [
        'colvis',
        'csv'
    ],
    dom: 'Bfrtip'
    } );

When I click on csv generation button, I have an issue when the plugin try to use "replace" function with a number (here 5421). See here.
Is it a good idea to convert all cell into a String before? like this (replace line 352):

tampon=a[i].toString();
            s += boundary ?
                boundary + tampon.replace( boundary, '\\'+boundary ) + boundary :
                a[i];

tampon was initiate before!

CSV commas not escaped properly

I have the following data value in one of my table cells: BUMPER-16",STL,CUST,TOW When using the html5 csv export I end up with several cells which look like

| BUMPER 16\ | STL | CR | TOW" |

Feature Request: Export Header / Footer options

Scenario: I'm currently using ajax in order to populate my datatables based upon some "fancy" parameter selector. So a user is picking selection criteria for the report. Now they want to export their data to excel / csv, etc etc. Unfortunately, when they do that, they have no way of telling what their selection criteria was upon export, so when they go back to that spreadsheet a week from now they might not have any idea what they are looking at.

I think it would be ideal to provide some functionality for including an export header / footer option. Even if it's just assigning some plain text to be included when present would be useful and ideally this should be able to be changed through an API call so that the header / footer could be changed as part of an ajax callback function.

null TypeError when printing table footer

I have a general table init options object. For the print button I use footer: true. Some tables have a total footer, some do not have any footer. When I click the print button for a table that does not have a footer the js crashes with TypeError: a is null.

Can't use colvis button when installed through npm

After installing datatables-buttons from npm, it seems to load properly, but throws this error when trying to use the colvis button: Cannot extend unknown button type: colvis

I've tried looking around for other npm packages like datatables-buttons-colvis, but I haven't been able to find any. Is there a way to use the column visibility plugin with the buttons npm package?

Column visibility doesn't work if data loading from server

Column visibility control will not work with next config:

$('#table').DataTable({
    "serverSide":true,
    "sAjaxSource":"http://localhost/users",
    "dom":"<\"dataTables_header\"Blfr>t<\"dataTables_footer\"ip>",
    "columns":[{
        "aTargets":"name",
        "mDataProp":"name",
        "title":"Name",
        "visible":true
    }, {
        "aTargets":"position",
        "mDataProp":"position",
        "title":"Position",
        "visible":true
    }],
    "buttons":[{"extend":"colvis","className":"button"}],
    "aaSorting":[[0,"asc"]]
});

You will get an empty box instead of column names
error

I've changed columnVisibility method in buttons.colVis.js:

//before
columnVisibility: {
    /*...*/
    text: function ( dt, button, conf ) {
        return $(dt.column( conf.columns ).header()).text();
    },
    /*...*/
},
//after
columnVisibility: {
    /*...*/
    text: function ( dt, button, conf ) {
        return dt.settings()[0].oInit.columns[conf.columns].title;
    },
    /*...*/
},

and it work fine for me. But I suppose that it will not work for usual tables. Maybe it should looks like:

columnVisibility: {
    /*...*/
    text: function ( dt, button, conf ) {
        return dt.settings()[0].sAjaxSource ? 
            dt.settings()[0].oInit.columns[conf.columns].title :
            $(dt.column( conf.columns ).header()).text();
    },
    /*...*/
},

Add friendly warning when dom: 'B' provided, but no button config

We run all of our tables through the same table initializer function. I had set dom: 'B...' as default, but in some cases, I added the buttons after initialization. Because B was set, but no config was present and this is undefined. It is called because the dom attr finds "B", i.e.:

// DataTables `dom` feature option
DataTable.ext.feature.push( {
    fnInit: function( settings ) {
        var api = new DataTable.Api( settings );
        var opts = api.init().buttons;

        return new Buttons( api, opts ).container();
    },
    cFeature: "B"
} );

This is not a datatables bug, but I thought it may be worth considering in the code snippet above to add a if ( !opts ) throw new ReferenceError('table initialized with Buttons pane location, but no buttons config'), or similar!

Just throwin' out ideas! Thanks,

Chris

Print view doesn't work if (typeof data == 'number')

Data for datatable:

{
  {id: 1, name: 'John Doe'},
  {id: 2, name: 'Jane Doe'}
}

I've got an error when trying to print table:

Uncaught TypeError: str.replace is not a function @ dataTables.buttons.js:1381

The problem is in strip function. You should check type of variable. For example:

var strip = function ( str ) {
    if (typeof str == 'number') {
        return str;
    }
    /*...*/
};

excelHtml5 action save zip files instead of xlsx

The problem: Saving the excel to disk, Firefox "Save As "dialog indicates that a zip file is going to be saved. This causes an error if "Open with" is used, since it is not an excel file.

The problematic code is:

        _saveAs(
            zip.generate( {type:"blob"} ),
            _filename( config )
        );

This code will apply the mime type zip.

Can be easily be patched by

        var dataArray = zip.generate( {type:"uint8array"} );
        _saveAs(
            new Blob([dataArray], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }),
            _filename( config )
        );

As patch

@@ -662,8 +662,9 @@
        xl_rels.file(       'workbook.xml.rels',   excelStrings['xl/_rels/workbook.xml.rels'] );
        xl_worksheets.file( 'sheet1.xml',          excelStrings['xl/worksheets/sheet1.xml'].replace( '__DATA__', xml ) );

+       var dataArray = zip.generate( {type:"uint8array"} );
        _saveAs(
-           zip.generate( {type:"blob"} ),
+           new Blob([dataArray], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }),
            _filename( config )
        );
    },

CSV HTML5: Only first instance of boundary is being escaped

When escaping boundary characters, currently only the first boundary that is found gets escaped. See http://jsfiddle.net/50x1m4bt/1/

A tweak to the first join of the _exportData function can correct the issue (notice the new "g" modifier for the replace)

var join = function ( a ) {
        var s = '';
        var boundary = config.fieldBoundary;
        var separator = config.fieldSeparator;

        // If there is a field boundary, then we might need to escape it in
        // the source data
        if (boundary) {
            var reg = new RegExp(boundary, "g");
        }
        for ( var i=0, ien=a.length ; i<ien ; i++ ) {
            if ( i > 0 ) {
                s += separator;
            }

            s += boundary ?
                boundary + a[i].replace( reg, '\'+boundary ) + boundary :
                a[i];
        }

        return s;
    };

add colspan support for footer

When printing a table with colspan in footer the cell is repeated with no colspan.

Example:

<tfoot>
    <tr>
        <th colspan="3">a</th>
        <th>b</th>
    </tr>
</tfoot>

results in

a a a b

Modifying cell data before export

I couldn't find example how to modify cell data before exporting to pdf or csv. In tablestools this was possible with fnCellRender. Is there something similar in Buttons?

Bootstrap integration on site

When viewing example of Buttons plugin with Bootstrap 3 integration (http://datatables.net/extensions/buttons/examples/styling/bootstrap.html) I noticed that buttons aren't styled correctly.
I get this:
snap 2015-08-20 at 15 47 08

When I think this should be result:

snap 2015-08-20 at 15 51 13

Problem occurs in http://datatables.net/media/css/site-examples.css file, that is overriding default Bootstrap style, maybe this can be fixed to show integration correctly?

Also there is small CSS bug: distance between table and buttons and between table and search input is different.

Provide a filename option and allow it to be a function

At the moment, the export files base the file name on the title parameter of the button configuration object. Really there should be a filename option so you can specify a title independently of the file name and it should be allowed to be a function so it can execute and return dynamic values.

Missing ui- class on DT defaults

Hey Allan!

Here you have defined the default classes for jquery ui buttons. I'm not a css design expert, but I think perhaps 'ui-corner-all' is missing? When I look at the jQuery theme roller site, the defaults have 'ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only'.

Feel free to close if it's a non issue. Thx!

-Chris

Title for buttons

It would be nice to have an option for setting attribute title for button. For example when using iconic buttons.

Export buttons error

When trying to use the CSV export button I'm getting an error on numeric data:
a[i].replace is not a function [buttons.html5.js - line 311]

This is the data in my table:

Department  Count
Support         2

I resolved the error by adding .toString() before the replace:

s += boundary ?
         boundary + a[i].toString().replace( boundary, '\\'+boundary ) + boundary :
         a[i];

Similar export code exists in buttons.flash.js

I hope this helps.

Excel export sometimes corrupt

Hey!

I'm having some funny issues with Button's Excel export. Sometimes Excel-file is corrupt - sometimes it works fine.
In both cases I can extract the files as zip - this it's not the the zipping that is the issue (I use latest JSZip v2.5.0-15).
I'm Ussing latest Buttons version 1.1.0.

First I thought the issue was because of special non-English characters - but both files are with non-English characters... Maybe issue is size/length/#row related or some encoding?

This file is corrupt:
https://www.dropbox.com/s/v7qw8xja6zslxx8/test-corrupt.xlsx

This file works fine:
https://www.dropbox.com/s/gmbc7i0u9vi3isv/test-works.xlsx

Both files are extractable - so maybe you can see more details about where exactly the issue is.

clicking CSV button gets Uncaught TypeError: a[i].replace is not a function

join                                @   buttons.html5.js:311
_exportData                     @   buttons.html5.js:323
DataTable.ext.buttons.csvHtml5.action   @   buttons.html5.js:482
(anonymous function)                @   dataTables.buttons.js:545
jQuery.event.dispatch               @   jquery-2.1.4.js:4435
jQuery.event.add.elemData.handle        @   jquery-2.1.4.js:4121

This is the code in question:

s += boundary ?
                boundary + a[i].replace( boundary, '\\'+boundary ) + boundary :
                a[i];

Error in file generated for excel

The excel file generated with excel button (both HTML5 and Flash) is corrupted if it has ~1500 or more rows. When I try to open the generated file in Excel 2013, it just shows a message saying that it found a problem with the file and asks if it can repair it. Clicking on repair doesn't solve the issue (not clicking either). I tried different datasets and still have same issue. From what I tested, it works fine if it has around 1200 rows or lower.
The layout is as following (7 columns):
[TextHeader][TextHeader][TextHeader][TextHeader][TextHeader][TextHeader][TextHeader]
[Text][Number][Date(dd/MM/yyyy)][Number][Number][Number][Text]

Thanks!

Allow for Pre and Post Actions.

I can't find a good way to do things before or after a buttons action has occurred.

Here's what I ended up doing.

I went in to https://github.com/DataTables/Buttons/blob/master/js/dataTables.buttons.js#L561 and added

if ( ! button.hasClass( buttonDom.disabled ) && config.preAction ){
    config.preAction.call( dt.button( button ), e, dt, button, config );
}

I would have done the same thing for postAction but that wouldn't support async actions.

https://github.com/DataTables/Buttons/blob/master/js/dataTables.buttons.js#L819 I added

if(conf.postAction){
    var _originalAction = conf.action;
    conf.action = function(e, dt, button, config){
        _originalAction.call(this, e, dt, button, config);
        conf.postAction.call(this, e, dt, button, config);
    }
}

That groups the execution of the postAction more tightly to the true finish of the button's Action.

These inclusions changed the way I had to do my lazy require I mentioned in #43.

Instead of being able to go straight to the html5 action I wanted and wrapping it in an async, I had to it after it had been attached to the buttons config, or it would do the same thing as if I'd put it inline with the preAction call.

So I had to commit a sin.

var _OriginalBuildButton = $.fn.dataTable.Buttons.prototype._buildButton;

$.fn.dataTable.Buttons.prototype._buildButton = function(conf, collectionButton){
    if(conf.name && conf.name === 'excel'){
        var originalAction = conf.action;
        conf.action = function(...args){
            require.ensure(['jszip'], function _excelHtml5Action(){
                // Exports the JSZip object. Up to us to strap it to the window.
                window.JSZip = require('jszip');
                originalAction(...args);
            }, 'datatable_exports_lazy')
        }
    }
    return _OriginalBuildButton.call(this, conf, collectionButton);
};

I added a name attr to all my actions for identification purposes.

If you have anything in mind for a better way to handle all this nonsense. Please

When can we expect Buttons 1.1.0?

Since the current dev-branch 1.1.0 of Buttons supports format in the exportOptions, I would like to know when we can expect the release of Buttons 1.1.0? Or better yet, can we expect dev-builds options in the Download builder any time soon?

Regards,
TK

Separate title & filename param values not working

When I set both the title and filename params, in that order, and separate values, it seems the title also takes on the filename param.

Tried with the bleeding edge copies of dataTables.buttons.js, buttons.bootstrap.js & buttons.html5.js

Possibly related to #20

Thanks in advance!

Loading JSZip and PDFMake scripts dynamically

@DataTables, as all we know and as you say "the disadvantage is that these files can significantly increase the amount of Javascript required on your page". It's not a good idea to load extra 500 kB library if it's not used everyday. And it's the only reason that stops me (and many other developers I think) from using it. Is it possible to load these libraries dynamically, only when user clicks "Export to PDF"/"Export to Excel" button for example? I'm not asking for solutions (code examples) here. I'm asking just about a possibility of that. And what do you think about this idea in general?

Spell Mismatch

Sorry, I couldn't find the respective page to make an update and PR.

On this page - http://datatables.net/extensions/buttons/config, Under Built in options category, Line as follows :
The Buttons library provides a number of core options that at common to all button types.
Should be
The Buttons library provides a number of core options that are common to all button types.

Problem with tfoot and thead in excel file

Hi,

I found one more issue with the generated excel file. When thead has multiple lines, it will only show the last one in the excel file, and tfoot content doesn't show at all.

Thanks!

Column Visiblility with Bootstrap Integration and Column Reorder

When working with Row Reorder and the bootstrap template integration the Column Visibility dropdown buttons break when a user reorders a column.

Before a user reorders a column, the buttons in the visibility dropdown are like:
<li class="dt-button buttons-columnVisibility" tabindex="0" aria-controls="CD_Data"><a>Address</a></li>
but after the columns are reordered the <a> tags around the 'column name' are missing on all of the buttons, so they are just plain text.

For reference I am using:
Bootstrap 3.3.5,
DataTables 1.10.9,
Buttons 1.0.3,
Column visibility 1.0.3,
and
ColReorder 1.2.0

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.