Subversion Repositories DevTools

Rev

Rev 6787 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
6651 dpurdie 1
/*
2
Based on the jQuery plugin found at http://www.kunalbabre.com/projects/TableCSVExport.php
3
Re-worked by ZachWick for LectureTools Inc. Sept. 2011
4
Copyright (c) 2011 LectureTools Inc.
5
 
6
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
7
 
8
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
9
 
10
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11
*/
12
/*
13
**  Vix: Minor modifications to:
14
**      Fill popup with entire TextArea
15
**      Only select td in the current table - prevent picking up bits from nested tables
6683 dpurdie 16
**      'th' with a class of 'noCsv' will exclude the entire column from the output
6695 dpurdie 17
**      The 'modal' display type
18
**      The 'title' option
6787 dpurdie 19
**      Use attribute of 'data-csv' if provided
6651 dpurdie 20
*/
21
jQuery.fn.TableCSVExport = function (options) {
22
    var options = jQuery.extend({
23
        separator: ',',
24
        header: [],
25
        columns: [],
26
        extraHeader: "",
27
        extraData: [],
28
        insertBefore: "",
6695 dpurdie 29
        delivery: 'popup' /* popup, value, download, modal */,
6651 dpurdie 30
        emptyValue: '',
31
        showHiddenRows: false,
32
	    rowFilter: "",
6695 dpurdie 33
	    filename: "download.csv",
34
        title : "CSV Data"
6651 dpurdie 35
    },
36
    options);
37
 
38
    var csvData = [];
39
    var headerArr = [];
40
    var el = this;
41
    var basic = options.columns.length == 0 ? true : false;
42
    var columnNumbers = [];
43
    var columnCounter = 0;
44
    var insertBeforeNum = null;
45
    //header
46
    var numCols = options.header.length;
47
    var tmpRow = []; // construct header avalible array
6683 dpurdie 48
    var incCol = [];
6651 dpurdie 49
 
50
    if (numCols > 0) {
51
        if (basic) {
52
            for (var i = 0; i < numCols; i++) {
53
                if (options.header[i] == options.insertBefore) {
54
                    tmpRow[tmpRow.length] = formatData(options.extraHeader);
55
                    insertBeforeNum = i;
56
                }
57
                tmpRow[tmpRow.length] = formatData(options.header[i]);
58
            }
59
        } else if (!basic) {
60
            for (var o = 0; o < numCols; o++) {
61
                for (var i = 0; i < options.columns.length; i++) {
62
                    if (options.columns[i] == options.header[o]) {
63
                        if (options.columns[i] == options.insertBefore) {
64
                            tmpRow[tmpRow.length] = formatData(options.extraHeader);
65
                            insertBeforeNum = o;
66
                        }
67
                        tmpRow[tmpRow.length] = formatData(options.header[o]);
68
                        columnNumbers[columnCounter] = o;
69
                        columnCounter++;
70
                    }
71
                }
72
            }
73
        }
74
    } else {
6683 dpurdie 75
        getAvailableElements(el).find('th').each(function (idx) {
76
            incCol[idx] = !jQuery(this).hasClass('noCsv');
77
            if ( incCol[idx] ) {
78
                if ( jQuery(this).css('display') != 'none' || options.showHiddenRows ) tmpRow[tmpRow.length] = formatData(jQuery(this).html());
79
            }
6651 dpurdie 80
        });
81
    }
82
 
83
    row2CSV(tmpRow);
84
 
85
    // actual data
86
    if (basic) {
87
        var trCounter = 0;
88
        getAvailableRows(el).each(function () {
89
            var tmpRow = [];
90
            var extraDataCounter = 0;
6683 dpurdie 91
            getAvailableElements(this).find('td').each(function (idx) {
92
                if ( incCol[idx] ) {
93
                    if ( extraDataCounter == insertBeforeNum )
94
                    {
95
                        tmpRow[tmpRow.length] = jQuery.trim(options.extraData[trCounter - 1]);
6651 dpurdie 96
                    }
6683 dpurdie 97
                    if (jQuery(this).css('display') != 'none' || options.showHiddenRows) {
6787 dpurdie 98
                        if ( jQuery(this).data('csv') ) {
6788 dpurdie 99
                            tmpRow[tmpRow.length] = formatData(jQuery(this).data('csv'));
100
                        } else if ( jQuery.trim(jQuery(this).html()) == "" ) {
6683 dpurdie 101
                            tmpRow[tmpRow.length] = formatData(options.emptyValue);
102
                        } else {
103
                            tmpRow[tmpRow.length] = jQuery.trim(formatData(jQuery(this).html()));
104
                        }
105
                    }
106
                    extraDataCounter++;
6651 dpurdie 107
                }
108
            });
109
            row2CSV(tmpRow);
110
            trCounter++;
111
        });
112
    } else {
113
        var trCounter = 0;
114
        getAvailableRows(el).each(function () {
115
            var tmpRow = [];
116
            var columnCounter = 0;
117
            var extraDataCounter = 0;
118
            getAvailableElements(this).find('td').each(function () {
119
                if ((columnCounter in columnNumbers) && (extraDataCounter == insertBeforeNum)) {
120
                    tmpRow[tmpRow.length] = jQuery.trim(formatData(options.extraData[trCounter - 1]));
121
                }
122
                if ((jQuery(this).css('display') != 'none' || options.showHiddenRows) && (columnCounter in columnNumbers)) {
123
                    tmpRow[tmpRow.length] = jQuery.trim(formatData(jQuery(this).html()));
124
                }
125
                columnCounter++;
126
                extraDataCounter++;
127
            });
128
            row2CSV(tmpRow);
129
            trCounter++;
130
        });
131
    }
132
 
133
    function getAvailableRows(el) {
134
        return jQuery(el).find('>tbody >tr' + options.rowFilter);
135
    }
136
 
137
    function getAvailableElements(el) {
138
        if (options.showHiddenRows) {
139
            return jQuery(el);
140
        } else {
141
            return jQuery(el).filter(':visible');
142
        }
143
    }
144
 
145
    if ((options.delivery == 'popup') || (options.delivery == 'download')) {
146
        var mydata = csvData.join('\n');
147
        return popup(mydata);
6695 dpurdie 148
    } else if ( options.delivery == 'modal' ) {
149
        var mydata = csvData.join('<br>');
150
        return popup(mydata);
6651 dpurdie 151
    } else {
152
        var mydata = csvData.join('\n');
153
        return mydata;
154
    }
155
 
156
    function row2CSV(tmpRow) {
157
        var tmp = tmpRow.join('') // to remove any blank rows
158
        // alert(tmp);
159
        if (tmpRow.length > 0 && tmp != '') {
160
            var mystr = tmpRow.join(options.separator);
161
            csvData[csvData.length] = jQuery.trim(mystr);
162
        }
163
    }
164
    function formatData(input) {
165
        // mask " with "
166
        var regexp = new RegExp(/["]/g); //"
167
        var output = input.replace(regexp, '""');
168
        // TODO: mask \""; at the end, so openoffice can open it correctly
169
 
170
        // strip HTML
171
        output = output.replace("<br>"," ");
172
        if(!( output != null && typeof output === 'object')) output = "<span>"+output+"</span>"; // to be able to use jquery
173
        output = $(output).text().trim();
174
 
175
        if (output == "") return '';
176
        return '"' + output + '"';
177
    }
6695 dpurdie 178
 
6651 dpurdie 179
    function popup(data) {
180
        if (options.delivery == 'download') {
181
            var blob = new Blob(['\ufeff'+data], { type: 'text/csv;charset=utf-8;' });
182
            if (navigator.msSaveBlob) { // IE 10+
183
                navigator.msSaveBlob(blob, options.filename);
184
            } else {
185
                var link = document.createElement("a");
186
                var url = URL.createObjectURL(blob);
187
                var isSafari = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1;
188
                if (isSafari) //if Safari open in new window to save file with random filename.
189
                    link.setAttribute("target", "_blank");
190
                link.setAttribute("href", url);
191
                link.setAttribute("download", options.filename);
192
                link.style = "visibility:hidden";
193
                document.body.appendChild(link);
194
                link.click();
195
                document.body.removeChild(link);
196
            }
197
            return true;
6695 dpurdie 198
        } else if (options.delivery == 'modal') {
199
            var newDiv = $(document.createElement('div'));
200
            $(newDiv).html(data);
201
            $(newDiv).dialog({width: 400, height: 400, modal:true, position: { my: "top", at: "top+100", of: window }, title: options.title});
202
            return true;
6651 dpurdie 203
        } else {
6695 dpurdie 204
            var generator = PopupCenter('', options.title, 600, 400);
205
            generator.document.write('<html><head><title>'+options.title+'</title>');
6651 dpurdie 206
            generator.document.write('</head><body >');
207
            generator.document.write('<textArea style="width:100%; height:100%;" wrap="off" >');
208
            generator.document.write(data);
209
            generator.document.write('</textArea>');
210
            generator.document.write('</body></html>');
211
            generator.document.close();
212
            return true;
213
        }
214
    }
215
};