Subversion Repositories DevTools

Rev

Rev 6695 | Go to most recent revision | 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') ) {
99
                            tmpRow[tmpRow.length] = formatData(jQuery(this).data('etext'));
100
                        }
101
                        else if ( jQuery.trim(jQuery(this).html()) == "" ) {
6683 dpurdie 102
                            tmpRow[tmpRow.length] = formatData(options.emptyValue);
103
                        } else {
104
                            tmpRow[tmpRow.length] = jQuery.trim(formatData(jQuery(this).html()));
105
                        }
106
                    }
107
                    extraDataCounter++;
6651 dpurdie 108
                }
109
            });
110
            row2CSV(tmpRow);
111
            trCounter++;
112
        });
113
    } else {
114
        var trCounter = 0;
115
        getAvailableRows(el).each(function () {
116
            var tmpRow = [];
117
            var columnCounter = 0;
118
            var extraDataCounter = 0;
119
            getAvailableElements(this).find('td').each(function () {
120
                if ((columnCounter in columnNumbers) && (extraDataCounter == insertBeforeNum)) {
121
                    tmpRow[tmpRow.length] = jQuery.trim(formatData(options.extraData[trCounter - 1]));
122
                }
123
                if ((jQuery(this).css('display') != 'none' || options.showHiddenRows) && (columnCounter in columnNumbers)) {
124
                    tmpRow[tmpRow.length] = jQuery.trim(formatData(jQuery(this).html()));
125
                }
126
                columnCounter++;
127
                extraDataCounter++;
128
            });
129
            row2CSV(tmpRow);
130
            trCounter++;
131
        });
132
    }
133
 
134
    function getAvailableRows(el) {
135
        return jQuery(el).find('>tbody >tr' + options.rowFilter);
136
    }
137
 
138
    function getAvailableElements(el) {
139
        if (options.showHiddenRows) {
140
            return jQuery(el);
141
        } else {
142
            return jQuery(el).filter(':visible');
143
        }
144
    }
145
 
146
    if ((options.delivery == 'popup') || (options.delivery == 'download')) {
147
        var mydata = csvData.join('\n');
148
        return popup(mydata);
6695 dpurdie 149
    } else if ( options.delivery == 'modal' ) {
150
        var mydata = csvData.join('<br>');
151
        return popup(mydata);
6651 dpurdie 152
    } else {
153
        var mydata = csvData.join('\n');
154
        return mydata;
155
    }
156
 
157
    function row2CSV(tmpRow) {
158
        var tmp = tmpRow.join('') // to remove any blank rows
159
        // alert(tmp);
160
        if (tmpRow.length > 0 && tmp != '') {
161
            var mystr = tmpRow.join(options.separator);
162
            csvData[csvData.length] = jQuery.trim(mystr);
163
        }
164
    }
165
    function formatData(input) {
166
        // mask " with "
167
        var regexp = new RegExp(/["]/g); //"
168
        var output = input.replace(regexp, '""');
169
        // TODO: mask \""; at the end, so openoffice can open it correctly
170
 
171
        // strip HTML
172
        output = output.replace("<br>"," ");
173
        if(!( output != null && typeof output === 'object')) output = "<span>"+output+"</span>"; // to be able to use jquery
174
        output = $(output).text().trim();
175
 
176
        if (output == "") return '';
177
        return '"' + output + '"';
178
    }
6695 dpurdie 179
 
6651 dpurdie 180
    function popup(data) {
181
        if (options.delivery == 'download') {
182
            var blob = new Blob(['\ufeff'+data], { type: 'text/csv;charset=utf-8;' });
183
            if (navigator.msSaveBlob) { // IE 10+
184
                navigator.msSaveBlob(blob, options.filename);
185
            } else {
186
                var link = document.createElement("a");
187
                var url = URL.createObjectURL(blob);
188
                var isSafari = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1;
189
                if (isSafari) //if Safari open in new window to save file with random filename.
190
                    link.setAttribute("target", "_blank");
191
                link.setAttribute("href", url);
192
                link.setAttribute("download", options.filename);
193
                link.style = "visibility:hidden";
194
                document.body.appendChild(link);
195
                link.click();
196
                document.body.removeChild(link);
197
            }
198
            return true;
6695 dpurdie 199
        } else if (options.delivery == 'modal') {
200
            var newDiv = $(document.createElement('div'));
201
            $(newDiv).html(data);
202
            $(newDiv).dialog({width: 400, height: 400, modal:true, position: { my: "top", at: "top+100", of: window }, title: options.title});
203
            return true;
6651 dpurdie 204
        } else {
6695 dpurdie 205
            var generator = PopupCenter('', options.title, 600, 400);
206
            generator.document.write('<html><head><title>'+options.title+'</title>');
6651 dpurdie 207
            generator.document.write('</head><body >');
208
            generator.document.write('<textArea style="width:100%; height:100%;" wrap="off" >');
209
            generator.document.write(data);
210
            generator.document.write('</textArea>');
211
            generator.document.write('</body></html>');
212
            generator.document.close();
213
            return true;
214
        }
215
    }
216
};