Subversion Repositories DevTools

Rev

Rev 6683 | Rev 6787 | 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
6651 dpurdie 19
*/
20
jQuery.fn.TableCSVExport = function (options) {
21
    var options = jQuery.extend({
22
        separator: ',',
23
        header: [],
24
        columns: [],
25
        extraHeader: "",
26
        extraData: [],
27
        insertBefore: "",
6695 dpurdie 28
        delivery: 'popup' /* popup, value, download, modal */,
6651 dpurdie 29
        emptyValue: '',
30
        showHiddenRows: false,
31
	    rowFilter: "",
6695 dpurdie 32
	    filename: "download.csv",
33
        title : "CSV Data"
6651 dpurdie 34
    },
35
    options);
36
 
37
    var csvData = [];
38
    var headerArr = [];
39
    var el = this;
40
    var basic = options.columns.length == 0 ? true : false;
41
    var columnNumbers = [];
42
    var columnCounter = 0;
43
    var insertBeforeNum = null;
44
    //header
45
    var numCols = options.header.length;
46
    var tmpRow = []; // construct header avalible array
6683 dpurdie 47
    var incCol = [];
6651 dpurdie 48
 
49
    if (numCols > 0) {
50
        if (basic) {
51
            for (var i = 0; i < numCols; i++) {
52
                if (options.header[i] == options.insertBefore) {
53
                    tmpRow[tmpRow.length] = formatData(options.extraHeader);
54
                    insertBeforeNum = i;
55
                }
56
                tmpRow[tmpRow.length] = formatData(options.header[i]);
57
            }
58
        } else if (!basic) {
59
            for (var o = 0; o < numCols; o++) {
60
                for (var i = 0; i < options.columns.length; i++) {
61
                    if (options.columns[i] == options.header[o]) {
62
                        if (options.columns[i] == options.insertBefore) {
63
                            tmpRow[tmpRow.length] = formatData(options.extraHeader);
64
                            insertBeforeNum = o;
65
                        }
66
                        tmpRow[tmpRow.length] = formatData(options.header[o]);
67
                        columnNumbers[columnCounter] = o;
68
                        columnCounter++;
69
                    }
70
                }
71
            }
72
        }
73
    } else {
6683 dpurdie 74
        getAvailableElements(el).find('th').each(function (idx) {
75
            incCol[idx] = !jQuery(this).hasClass('noCsv');
76
            if ( incCol[idx] ) {
77
                if ( jQuery(this).css('display') != 'none' || options.showHiddenRows ) tmpRow[tmpRow.length] = formatData(jQuery(this).html());
78
            }
6651 dpurdie 79
        });
80
    }
81
 
82
    row2CSV(tmpRow);
83
 
84
    // actual data
85
    if (basic) {
86
        var trCounter = 0;
87
        getAvailableRows(el).each(function () {
88
            var tmpRow = [];
89
            var extraDataCounter = 0;
6683 dpurdie 90
            getAvailableElements(this).find('td').each(function (idx) {
91
                if ( incCol[idx] ) {
92
                    if ( extraDataCounter == insertBeforeNum )
93
                    {
94
                        tmpRow[tmpRow.length] = jQuery.trim(options.extraData[trCounter - 1]);
6651 dpurdie 95
                    }
6683 dpurdie 96
                    if (jQuery(this).css('display') != 'none' || options.showHiddenRows) {
97
                        if (jQuery.trim(jQuery(this).html()) == "") {
98
                            tmpRow[tmpRow.length] = formatData(options.emptyValue);
99
                        } else {
100
                            tmpRow[tmpRow.length] = jQuery.trim(formatData(jQuery(this).html()));
101
                        }
102
                    }
103
                    extraDataCounter++;
6651 dpurdie 104
                }
105
            });
106
            row2CSV(tmpRow);
107
            trCounter++;
108
        });
109
    } else {
110
        var trCounter = 0;
111
        getAvailableRows(el).each(function () {
112
            var tmpRow = [];
113
            var columnCounter = 0;
114
            var extraDataCounter = 0;
115
            getAvailableElements(this).find('td').each(function () {
116
                if ((columnCounter in columnNumbers) && (extraDataCounter == insertBeforeNum)) {
117
                    tmpRow[tmpRow.length] = jQuery.trim(formatData(options.extraData[trCounter - 1]));
118
                }
119
                if ((jQuery(this).css('display') != 'none' || options.showHiddenRows) && (columnCounter in columnNumbers)) {
120
                    tmpRow[tmpRow.length] = jQuery.trim(formatData(jQuery(this).html()));
121
                }
122
                columnCounter++;
123
                extraDataCounter++;
124
            });
125
            row2CSV(tmpRow);
126
            trCounter++;
127
        });
128
    }
129
 
130
    function getAvailableRows(el) {
131
        return jQuery(el).find('>tbody >tr' + options.rowFilter);
132
    }
133
 
134
    function getAvailableElements(el) {
135
        if (options.showHiddenRows) {
136
            return jQuery(el);
137
        } else {
138
            return jQuery(el).filter(':visible');
139
        }
140
    }
141
 
142
    if ((options.delivery == 'popup') || (options.delivery == 'download')) {
143
        var mydata = csvData.join('\n');
144
        return popup(mydata);
6695 dpurdie 145
    } else if ( options.delivery == 'modal' ) {
146
        var mydata = csvData.join('<br>');
147
        return popup(mydata);
6651 dpurdie 148
    } else {
149
        var mydata = csvData.join('\n');
150
        return mydata;
151
    }
152
 
153
    function row2CSV(tmpRow) {
154
        var tmp = tmpRow.join('') // to remove any blank rows
155
        // alert(tmp);
156
        if (tmpRow.length > 0 && tmp != '') {
157
            var mystr = tmpRow.join(options.separator);
158
            csvData[csvData.length] = jQuery.trim(mystr);
159
        }
160
    }
161
    function formatData(input) {
162
        // mask " with "
163
        var regexp = new RegExp(/["]/g); //"
164
        var output = input.replace(regexp, '""');
165
        // TODO: mask \""; at the end, so openoffice can open it correctly
166
 
167
        // strip HTML
168
        output = output.replace("<br>"," ");
169
        if(!( output != null && typeof output === 'object')) output = "<span>"+output+"</span>"; // to be able to use jquery
170
        output = $(output).text().trim();
171
 
172
        if (output == "") return '';
173
        return '"' + output + '"';
174
    }
6695 dpurdie 175
 
6651 dpurdie 176
    function popup(data) {
177
        if (options.delivery == 'download') {
178
            var blob = new Blob(['\ufeff'+data], { type: 'text/csv;charset=utf-8;' });
179
            if (navigator.msSaveBlob) { // IE 10+
180
                navigator.msSaveBlob(blob, options.filename);
181
            } else {
182
                var link = document.createElement("a");
183
                var url = URL.createObjectURL(blob);
184
                var isSafari = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1;
185
                if (isSafari) //if Safari open in new window to save file with random filename.
186
                    link.setAttribute("target", "_blank");
187
                link.setAttribute("href", url);
188
                link.setAttribute("download", options.filename);
189
                link.style = "visibility:hidden";
190
                document.body.appendChild(link);
191
                link.click();
192
                document.body.removeChild(link);
193
            }
194
            return true;
6695 dpurdie 195
        } else if (options.delivery == 'modal') {
196
            var newDiv = $(document.createElement('div'));
197
            $(newDiv).html(data);
198
            $(newDiv).dialog({width: 400, height: 400, modal:true, position: { my: "top", at: "top+100", of: window }, title: options.title});
199
            return true;
6651 dpurdie 200
        } else {
6695 dpurdie 201
            var generator = PopupCenter('', options.title, 600, 400);
202
            generator.document.write('<html><head><title>'+options.title+'</title>');
6651 dpurdie 203
            generator.document.write('</head><body >');
204
            generator.document.write('<textArea style="width:100%; height:100%;" wrap="off" >');
205
            generator.document.write(data);
206
            generator.document.write('</textArea>');
207
            generator.document.write('</body></html>');
208
            generator.document.close();
209
            return true;
210
        }
211
    }
212
};