123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139 |
- /**
- * SheetClip - Spreadsheet Clipboard Parser
- * version 0.3
- *
- * This tiny library transforms JavaScript arrays to strings that are pasteable by LibreOffice, OpenOffice,
- * Google Docs and Microsoft Excel.
- *
- * Copyright 2012, Marcin Warpechowski
- * Licensed under the MIT license.
- * http://github.com/warpech/sheetclip/
- */
- /*jslint white: true*/
- (function (scope)
- {
- "use strict";
- // Class Definition
- function SheetClip ()
- {
-
- }
-
- SheetClip.prototype = Object.create(Object.prototype,
- {
- parse:
- {
- value: function (str)
- {
- var r, rlen, rows, arr = [], a = 0, c, clen, multiline, last;
- rows = str.split('\n');
-
- if (rows.length > 1 && rows[rows.length - 1] === '')
- rows.pop();
-
- for (r = 0, rlen = rows.length; r < rlen; r += 1)
- {
- rows[r] = rows[r].split('\t');
-
- for (c = 0, clen = rows[r].length; c < clen; c += 1)
- {
- if (!arr[a])
- arr[a] = [];
-
- if (multiline && c === 0)
- {
- last = arr[a].length - 1;
- arr[a][last] = arr[a][last] + '\n' + rows[r][0];
-
- if (multiline && (countQuotes(rows[r][0]) & 1))
- { //& 1 is a bitwise way of performing mod 2
- multiline = false;
- arr[a][last] = arr[a][last].substring(0, arr[a][last].length - 1).replace(/""/g, '"');
- }
- }
- else
- {
- if (c === clen - 1 && rows[r][c].indexOf('"') === 0 && (countQuotes(rows[r][c]) & 1))
- {
- arr[a].push(rows[r][c].substring(1).replace(/""/g, '"'));
- multiline = true;
- }
- else
- {
- arr[a].push(rows[r][c].replace(/""/g, '"'));
- multiline = false;
- }
- }
- }
-
- if (!multiline)
- a += 1;
- }
-
- return arr;
- },
- enumerable: true,
- configurable: false,
- writable: false
- },
-
- stringify:
- {
- value: function (arr)
- {
- var r, rlen, c, clen, str = '', val;
-
- for (r = 0, rlen = arr.length; r < rlen; r += 1)
- {
- for (c = 0, clen = arr[r].length; c < clen; c += 1)
- {
- if (c > 0)
- str += '\t';
-
- val = arr[r][c];
-
- if (typeof val === 'string')
- {
- if (val.indexOf('\n') > -1)
- {
- str += '"' + val.replace(/"/g, '""') + '"';
- }
- else
- {
- str += val;
- }
- }
- else
- if (val === null || val === void 0)
- { //void 0 resolves to undefined
- str += '';
- }
- else
- {
- str += val;
- }
- }
-
- str += '\n';
- }
- return str;
- },
- enumerable: true,
- configurable: false,
- writable: false
- }
- });
-
- // Private Static Functions
- function countQuotes(str)
- {
- return str.split('"').length - 1;
- }
-
- if (typeof module !== "undefined" && module.exports)
- module.exports = SheetClip;
- else
- scope.SheetClip = SheetClip;
- }(this));
|