Subversion Repositories DevTools

Rev

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