@syncfusion/ej2-excel-export
Version:
Essential Javascript 2 Excel Export Library
1,361 lines (1,349 loc) • 111 kB
JavaScript
import { ZipArchive, ZipArchiveItem } from '@syncfusion/ej2-compression';
import { Internationalization, isNullOrUndefined } from '@syncfusion/ej2-base';
import { Encoding } from '@syncfusion/ej2-file-utils';
/**
* CellStyle class
* @private
*/
/* eslint-disable */
class CellStyle {
constructor() {
this.numFmtId = 0;
this.backColor = 'none';
this.fontName = 'Calibri';
this.fontSize = 10.5;
this.fontColor = '#000000';
this.italic = false;
this.bold = false;
this.underline = false;
this.strikeThrough = false;
this.wrapText = false;
this.hAlign = 'general';
this.vAlign = 'bottom';
this.indent = 0;
this.rotation = 0;
this.numberFormat = 'GENERAL';
this.type = 'datetime';
this.borders = new Borders();
this.isGlobalStyle = false;
}
}
/**
* Font Class
* @private
*/
class Font {
constructor() {
this.sz = 10.5;
this.name = 'Calibri';
this.u = false;
this.b = false;
this.i = false;
this.color = 'FF000000';
this.strike = false;
}
}
/**
* CellXfs class
* @private
*/
class CellXfs {
}
/**
* Alignment class
* @private
*/
class Alignment {
}
/**
* CellStyleXfs class
* @private
*/
class CellStyleXfs {
}
/**
* CellStyles class
* @private
*/
class CellStyles {
constructor() {
this.name = 'Normal';
this.xfId = 0;
}
}
/**
* NumFmt class
* @private
*/
class NumFmt {
constructor(id, code) {
this.numFmtId = id;
this.formatCode = code;
}
}
/**
* Border class
* @private
*/
class Border {
constructor(mLine, mColor) {
this.lineStyle = mLine;
this.color = mColor;
}
}
/**
* Borders class
* @private
*/
class Borders {
constructor() {
this.left = new Border('none', '#FFFFFF');
this.right = new Border('none', '#FFFFFF');
this.top = new Border('none', '#FFFFFF');
this.bottom = new Border('none', '#FFFFFF');
this.all = new Border('none', '#FFFFFF');
}
}
/**
* Worksheet class
* @private
*/
/* eslint-disable */
class Cell {
}
/**
* Cells class
* @private
*/
class Cells extends Array {
constructor() {
super(...arguments);
this.add = (cell) => {
let inserted = false;
let count = 0;
for (let c of this) {
if (c.index === cell.index) {
this[count] = cell;
inserted = true;
}
count++;
}
if (!inserted) {
this.push(cell);
}
};
}
}
/**
* Column class
* @private
*/
/* eslint-disable */
class Column {
}
/**
* Row class
* @private
*/
/* eslint-disable */
class Row {
}
/**
* Rows class
* @private
*/
class Rows extends Array {
constructor() {
super(...arguments);
this.add = (row) => {
this.push(row);
};
}
}
/**
* Worksheets class
* @private
*/
/* eslint-disable */
class Worksheets extends Array {
}
/**
* Worksheet class
* @private
*/
/* eslint-disable */
class Worksheet {
constructor() {
this.isSummaryRowBelow = true;
this.showGridLines = true;
this.enableRtl = false;
}
}
/**
* Hyperlink class
* @private
*/
class HyperLink {
}
/**
* Grouping class
* @private
*/
class Grouping {
}
/**
* FreezePane class
* @private
*/
class FreezePane {
}
/**
* MergeCell
* @private
*/
class MergeCell {
}
/**
* MergeCells class
* @private
*/
class MergeCells extends Array {
constructor() {
super(...arguments);
this.add = (mergeCell) => {
let inserted = false;
let count = 0;
for (let mCell of this) {
if (MergeCells.isIntersecting(mCell, mergeCell)) {
let intersectingCell = new MergeCell();
intersectingCell.x = Math.min(mCell.x, mergeCell.x);
intersectingCell.y = Math.min(mCell.Y, mergeCell.y);
intersectingCell.width = Math.max(mCell.Width + mCell.X, mergeCell.width + mergeCell.x);
intersectingCell.height = Math.max(mCell.Height + mCell.Y, mergeCell.height + mergeCell.y);
intersectingCell.ref = (this[count].ref.split(':')[0]) + ':' + (mergeCell.ref.split(':')[1]);
this[count] = intersectingCell;
mergeCell = intersectingCell;
inserted = true;
}
count++;
}
if (!inserted) {
this.push(mergeCell);
}
return mergeCell;
};
}
static isIntersecting(base, compare) {
return (base.x <= compare.x + compare.width)
&& (compare.x <= base.x + base.width)
&& (base.y <= compare.y + compare.height)
&& (compare.y <= base.y + base.height);
}
}
/**
* Image class
* @private
*/
/* eslint-disable */
class Image {
}
// import { IValueFormatter } from '../base/interface';
/**
* ValueFormatter class to globalize the value.
* @private
*/
/* eslint-disable */
class ValueFormatter {
constructor(cultureName) {
this.intl = new Internationalization();
// if (!isNullOrUndefined(cultureName)) {
// this.intl.culture = cultureName;
// }
}
getFormatFunction(format, isServerRendered) {
if (format.type) {
if (isServerRendered) {
format.isServerRendered = true;
}
return this.intl.getDateFormat(format);
}
else {
return this.intl.getNumberFormat(format);
}
}
// public getParserFunction(format: NumberFormatOptions | DateFormatOptions): Function {
// if ((<DateFormatOptions>format).type) {
// return this.intl.getDateParser(<DateFormatOptions>format);
// } else {
// return this.intl.getNumberParser(<DateFormatOptions>format);
// }
// }
// public fromView(value: string, format: Function, type?: string): string | number | Date {
// if (type === 'date' || type === 'datetime' || type === 'number') {
// return format(value);
// } else {
// return value;
// }
// }
toView(value, format) {
let result = value;
if (!isNullOrUndefined(format) && !isNullOrUndefined(value)) {
result = format(value);
}
return result;
}
// public setCulture(cultureName: string): void {
// if (!isNullOrUndefined(cultureName)) {
// setCulture(cultureName);
// }
// }
/* tslint:disable:no-any */
displayText(value, format, isServerRendered) {
return this.toView(value, this.getFormatFunction(format, isServerRendered));
}
}
/**
* CsvHelper class
* @private
*/
/* eslint-disable */
class CsvHelper {
/* tslint:disable:no-any */
constructor(json, separator, qualifier, newLine) {
this.lineSeparator = '\r\n'; // default CRLF
this.csvStr = '';
if (separator === null || separator === undefined) {
this.separator = ',';
}
else {
this.separator = separator;
}
this.qualifier = (qualifier === undefined) ? '"' : qualifier;
this.lineSeparator = this.GetLineSeparator(newLine);
this.formatter = new ValueFormatter();
this.isMicrosoftBrowser = !(!navigator.msSaveBlob);
if (json.isServerRendered !== null && json.isServerRendered !== undefined) {
this.isServerRendered = json.isServerRendered;
}
if (json.styles !== null && json.styles !== undefined) {
this.globalStyles = new Map();
for (let i = 0; i < json.styles.length; i++) {
if (json.styles[i].name !== undefined && json.styles[i].numberFormat !== undefined) {
this.globalStyles.set(json.styles[i].name, json.styles[i].numberFormat);
}
}
}
// Parses Worksheets data to DOM.
if (json.worksheets !== null && json.worksheets !== undefined) {
this.parseWorksheet(json.worksheets[0]);
}
//this.csvStr = 'a1,a2,a3\nb1,b2,b3';
}
GetLineSeparator(newLine) {
if (!newLine) {
return '\r\n';
}
const map = { CRLF: '\r\n', LF: '\n', CR: '\r' };
return (newLine in map) ? map[newLine] : String(newLine);
}
parseWorksheet(json) {
//Rows
if (json.rows !== null && json.rows !== undefined) {
this.parseRows(json.rows);
}
}
/* tslint:disable:no-any */
parseRows(rows) {
let count = 1;
for (let row of rows) {
//Row index
if (row.index !== null && row.index !== undefined) {
while (count < row.index) {
this.csvStr += this.lineSeparator;
count++;
}
this.parseRow(row);
}
else {
throw Error('Row index is missing.');
}
}
this.csvStr += this.lineSeparator;
}
/* tslint:disable:no-any */
parseRow(row) {
if (row.cells !== null && row.cells !== undefined) {
let count = 1;
for (let cell of row.cells) {
//cell index
if (cell.index !== null && cell.index !== undefined) {
while (count < cell.index) {
this.csvStr += this.separator;
count++;
}
this.parseCell(cell);
}
else {
throw Error('Cell index is missing.');
}
}
}
}
/* tslint:disable:no-any */
parseCell(cell) {
let csv = this.csvStr;
if (cell.value !== undefined) {
if (cell.value instanceof Date) {
if (cell.style !== undefined && cell.style.numberFormat !== undefined) {
/* tslint:disable-next-line:max-line-length */
try {
csv += this.parseCellValue(this.formatter.displayText(cell.value, { type: 'dateTime', skeleton: cell.style.numberFormat }, this.isServerRendered));
}
catch (error) {
/* tslint:disable-next-line:max-line-length */
csv += this.parseCellValue(this.formatter.displayText(cell.value, { type: 'dateTime', format: cell.style.numberFormat }, this.isServerRendered));
}
}
else if (cell.style !== undefined && cell.style.name !== undefined && this.globalStyles.has(cell.style.name)) {
/* tslint:disable-next-line:max-line-length */
try {
csv += this.parseCellValue(this.formatter.displayText(cell.value, { type: 'dateTime', skeleton: this.globalStyles.get(cell.style.name) }, this.isServerRendered));
}
catch (error) {
/* tslint:disable-next-line:max-line-length */
csv += this.parseCellValue(this.formatter.displayText(cell.value, { type: 'dateTime', format: this.globalStyles.get(cell.style.name) }, this.isServerRendered));
}
}
else {
csv += cell.value;
}
}
else if (typeof (cell.value) === 'boolean') {
csv += cell.value ? 'TRUE' : 'FALSE';
}
else if (typeof (cell.value) === 'number') {
if (cell.style !== undefined && cell.style.numberFormat !== undefined) {
/* tslint:disable-next-line:max-line-length */
csv += this.parseCellValue(this.formatter.displayText(cell.value, { format: cell.style.numberFormat, ignoreCurrency: true }, this.isServerRendered));
}
else if (cell.style !== undefined && cell.style.name !== undefined && this.globalStyles.has(cell.style.name)) {
/* tslint:disable-next-line:max-line-length */
csv += this.parseCellValue(this.formatter.displayText(cell.value, { format: this.globalStyles.get(cell.style.name), ignoreCurrency: true }, this.isServerRendered));
}
else {
csv += cell.value;
}
}
else {
csv += this.parseCellValue(cell.value);
}
}
this.csvStr = csv;
}
parseCellValue(value) {
const csvLineSeparator = (this.separator !== undefined && this.separator !== null) ? this.separator : ','; // field delimiter
const csvQualifier = (this.qualifier && this.qualifier.length > 0) ? this.qualifier : '"';
const newLine = this.lineSeparator || '\r\n'; // configured newline sequence
if (value == null)
return '';
// Normalize all newline variants to the configured newline sequence
const normalized = String(value).replace(/\r\n|\n|\r/g, newLine);
// Detect if the value is already wrapped with the qualifier
const alreadyQualified = normalized.startsWith(csvQualifier) && normalized.endsWith(csvQualifier);
// Escape qualifiers by doubling them (avoid touching the outer pair if already qualified)
let escaped = '';
for (let i = 0; i < normalized.length; i++) {
const ch = normalized[i];
// Preserve the first/last char if they are the wrapping qualifiers
if (alreadyQualified && (i === 0 || i === normalized.length - 1)) {
escaped += ch;
continue;
}
escaped += (ch === csvQualifier) ? (csvQualifier + csvQualifier) : ch;
}
// Quote when needed: contains delimiter, qualifier, or newline, or has leading/trailing whitespace
const mustQuote = escaped.includes(csvLineSeparator) ||
escaped.includes(csvQualifier) ||
escaped.includes(newLine) ||
/^\s/.test(escaped) ||
/\s$/.test(escaped);
if (alreadyQualified)
return escaped;
return mustQuote ? (csvQualifier + escaped + csvQualifier) : escaped;
}
/**
* Saves the file with specified name and sends the file to client browser
* @param {string} fileName- file name to save.
* @param {Blob} buffer- the content to write in file
*/
save(fileName) {
this.buffer = new Blob(['\ufeff' + this.csvStr], { type: 'text/csv;charset=UTF-8' });
if (this.isMicrosoftBrowser) {
navigator.msSaveBlob(this.buffer, fileName);
}
else {
let dataUrl = window.URL.createObjectURL(this.buffer);
let dwlLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
dwlLink.download = fileName;
dwlLink.href = dataUrl;
let event = document.createEvent('MouseEvent');
event.initEvent('click', true, true);
dwlLink.dispatchEvent(event);
setTimeout(() => {
window.URL.revokeObjectURL(dataUrl);
});
}
}
/**
* Returns a Blob object containing CSV data with optional encoding.
* @param {string} [encodingType] - The supported encoding types are "ansi", "unicode" and "utf8".
*/
/* tslint:disable:no-any */
saveAsBlob(encodingType) {
if (encodingType != undefined) {
let encoding = new Encoding();
let encodeString = 'UTF-8';
if (encodingType.toUpperCase() == "ANSI") {
encoding.type = 'Ansi';
encodeString = 'ANSI';
}
else if (encodingType.toUpperCase() == "UNICODE") {
encoding.type = 'Unicode';
encodeString = 'UNICODE';
}
else {
encoding.type = 'Utf8';
encodeString = 'UTF-8';
}
let buffer = encoding.getBytes(this.csvStr, 0, this.csvStr.length);
return new Blob([buffer], { type: 'text/csv;charset=' + encodeString });
}
else
return new Blob(['\ufeff' + this.csvStr], { type: 'text/csv;charset=UTF-8' });
}
}
/**
* BlobHelper class
* @private
*/
/* eslint-disable */
class BlobHelper {
constructor() {
/* tslint:disable:no-any */
this.parts = [];
}
/* tslint:disable:no-any */
append(part) {
this.parts.push(part);
this.blob = undefined; // Invalidate the blob
}
getBlob() {
return new Blob(this.parts, { type: 'text/plain' });
}
}
/**
* AutoFilters class
* @private
*/
/* eslint-disable */
class AutoFilters {
}
/**
* Workbook class
*/
/* eslint-disable */
class Workbook {
/* tslint:disable:no-any */
constructor(json, saveType, culture, currencyString, separator) {
this.sharedStringCount = 0;
this.csvLineSeparator = 'CRLF';
this.csvQualifier = '"'; // default
this.unitsProportions = [
96 / 75.0,
96 / 300.0,
96,
96 / 25.4,
96 / 2.54,
1,
96 / 72.0,
96 / 72.0 / 12700,
];
/* tslint:disable:no-any */
this.hyperlinkStyle = { fontColor: '#0000FF', underline: true };
if (culture !== undefined) {
this.culture = culture;
}
else {
this.culture = 'en-US';
}
if (currencyString !== undefined) {
this.currency = currencyString;
}
else {
this.currency = 'USD';
}
this.intl = new Internationalization(this.culture);
this.mSaveType = saveType;
if (saveType === 'xlsx') {
this.mArchive = new ZipArchive();
this.sharedString = [];
this.mFonts = [];
this.mBorders = [];
this.mStyles = [];
this.printTitles = new Map();
this.cellStyles = new Map();
this.mNumFmt = new Map();
this.mFills = new Map();
this.mStyles.push(new CellStyle());
this.mFonts.push(new Font());
/* tslint:disable */
this.cellStyles.set('Normal', new CellStyles());
/* tslint:enable */
this.mCellXfs = [];
this.mCellStyleXfs = [];
this.drawingCount = 0;
this.imageCount = 0;
if (json.styles !== null && json.styles !== undefined) {
/* tslint:disable-next-line:no-any */
this.globalStyles = new Map();
for (let i = 0; i < json.styles.length; i++) {
if (json.styles[i].name !== undefined) {
if (!this.cellStyles.has(json.styles[i].name)) {
let cellStyle = new CellStyle();
cellStyle.isGlobalStyle = true;
this.parserCellStyle(json.styles[i], cellStyle, 'none');
let cellStylesIn = new CellStyles();
cellStylesIn.name = cellStyle.name;
cellStylesIn.xfId = (cellStyle.index - 1);
this.cellStyles.set(cellStylesIn.name, cellStylesIn);
/* tslint:disable-next-line:no-any */
let tFormat = {};
if (json.styles[i].numberFormat !== undefined) {
tFormat.format = json.styles[i].numberFormat;
}
if (json.styles[i].type !== undefined) {
tFormat.type = json.styles[i].type;
}
else {
tFormat.type = 'datetime';
}
if (tFormat.format !== undefined) {
this.globalStyles.set(json.styles[i].name, tFormat);
}
}
else {
throw Error('Style name ' + json.styles[i].name + ' is already existed');
}
}
}
}
// Parses Worksheets data to DOM.
if (json.worksheets !== null && json.worksheets !== undefined) {
this.parserWorksheets(json.worksheets);
}
else {
throw Error('Worksheet is expected.');
}
// Parses the BuiltInProperties data to DOM.
if (json.builtInProperties !== null && json.builtInProperties !== undefined) {
this.builtInProperties = new BuiltInProperties();
this.parserBuiltInProperties(json.builtInProperties, this.builtInProperties);
}
}
else {
if (json && json.csvQualifier != null) {
this.csvQualifier = String(json.csvQualifier);
}
if (json && json.csvLineSeparator !== null) {
this.csvLineSeparator = json.csvLineSeparator;
}
this.csvHelper = new CsvHelper(json, separator, this.csvQualifier, this.csvLineSeparator);
}
}
/* tslint:disable:no-any */
parserBuiltInProperties(jsonBuiltInProperties, builtInProperties) {
//Author
if (jsonBuiltInProperties.author !== null && jsonBuiltInProperties.author !== undefined) {
builtInProperties.author = jsonBuiltInProperties.author;
}
//Comments
if (jsonBuiltInProperties.comments !== null && jsonBuiltInProperties.comments !== undefined) {
builtInProperties.comments = jsonBuiltInProperties.comments;
}
//Category
if (jsonBuiltInProperties.category !== null && jsonBuiltInProperties.category !== undefined) {
builtInProperties.category = jsonBuiltInProperties.category;
}
//Company
if (jsonBuiltInProperties.company !== null && jsonBuiltInProperties.company !== undefined) {
builtInProperties.company = jsonBuiltInProperties.company;
}
//Manager
if (jsonBuiltInProperties.manager !== null && jsonBuiltInProperties.manager !== undefined) {
builtInProperties.manager = jsonBuiltInProperties.manager;
}
//Subject
if (jsonBuiltInProperties.subject !== null && jsonBuiltInProperties.subject !== undefined) {
builtInProperties.subject = jsonBuiltInProperties.subject;
}
//Title
if (jsonBuiltInProperties.title !== null && jsonBuiltInProperties.title !== undefined) {
builtInProperties.title = jsonBuiltInProperties.title;
}
//Creation date
if (jsonBuiltInProperties.createdDate !== null && jsonBuiltInProperties.createdDate !== undefined) {
builtInProperties.createdDate = jsonBuiltInProperties.createdDate;
}
//Modified date
if (jsonBuiltInProperties.modifiedDate !== null && jsonBuiltInProperties.modifiedDate !== undefined) {
builtInProperties.modifiedDate = jsonBuiltInProperties.modifiedDate;
}
//Tags
if (jsonBuiltInProperties.tags !== null && jsonBuiltInProperties.tags !== undefined) {
builtInProperties.tags = jsonBuiltInProperties.tags;
}
//Status
if (jsonBuiltInProperties.status !== null && jsonBuiltInProperties.status !== undefined) {
builtInProperties.status = jsonBuiltInProperties.status;
}
}
/* tslint:disable:no-any */
parserWorksheets(json) {
this.worksheets = new Worksheets();
let length = json.length;
for (let i = 0; i < length; i++) {
let jsonSheet = json[i];
let sheet = new Worksheet();
this.mergeCells = new MergeCells();
this.mergedCellsStyle = new Map();
this.mHyperLinks = [];
//Name
if (jsonSheet.name !== null && jsonSheet.name !== undefined) {
sheet.name = jsonSheet.name;
}
else {
sheet.name = 'Sheet' + (i + 1).toString();
}
if (jsonSheet.enableRtl !== null && jsonSheet.enableRtl !== undefined) {
sheet.enableRtl = jsonSheet.enableRtl;
}
sheet.index = (i + 1);
//Columns
if (jsonSheet.columns !== null && jsonSheet.columns !== undefined) {
this.parserColumns(jsonSheet.columns, sheet);
}
//Rows
if (jsonSheet.rows !== null && jsonSheet.rows !== undefined) {
this.parserRows(jsonSheet.rows, sheet);
}
//showGridLines
if (jsonSheet.showGridLines !== null && jsonSheet.showGridLines !== undefined) {
sheet.showGridLines = jsonSheet.showGridLines;
}
//FreezePanes
if (jsonSheet.freeze !== null && jsonSheet.freeze !== undefined) {
this.parserFreezePanes(jsonSheet.freeze, sheet);
}
//Print Title
if (jsonSheet.printTitle !== null && jsonSheet.printTitle !== undefined) {
this.parserPrintTitle(jsonSheet.printTitle, sheet);
}
if (jsonSheet.pageSetup !== undefined) {
if (jsonSheet.pageSetup.isSummaryRowBelow !== undefined) {
sheet.isSummaryRowBelow = jsonSheet.pageSetup.isSummaryRowBelow;
}
}
if (jsonSheet.images !== undefined) {
this.parserImages(jsonSheet.images, sheet);
}
if (jsonSheet.autoFilters !== null && jsonSheet.autoFilters !== undefined) {
this.parseFilters(jsonSheet.autoFilters, sheet);
}
sheet.index = (i + 1);
sheet.mergeCells = this.mergeCells;
sheet.hyperLinks = this.mHyperLinks;
this.worksheets.push(sheet);
}
}
/* tslint:disable:no-any */
mergeOptions(fromJson, toJson) {
/* tslint:disable:no-any */
let result = {};
this.applyProperties(fromJson, result);
this.applyProperties(toJson, result);
return result;
}
/* tslint:disable:no-any */
applyProperties(sourceJson, destJson) {
let keys = Object.keys(sourceJson);
for (let index = 0; index < keys.length; index++) {
if (keys[index] !== 'name') {
destJson[keys[index]] = sourceJson[keys[index]];
}
}
}
getCellName(row, column) {
return this.getColumnName(column) + row.toString();
}
getColumnName(col) {
col--;
let strColumnName = '';
do {
let iCurrentDigit = col % 26;
col = col / 26 - 1;
strColumnName = String.fromCharCode(65 + iCurrentDigit) + strColumnName;
} while (col >= 0);
return strColumnName;
}
/* tslint:disable:no-any */
parserPrintTitle(json, sheet) {
let printTitleName = '';
let titleRowName;
if (json.fromRow !== null && json.fromRow !== undefined) {
let fromRow = json.fromRow;
let toRow;
if (json.toRow !== null && json.toRow !== undefined) {
toRow = json.toRow;
}
else {
toRow = json.fromRow;
}
titleRowName = '$' + fromRow + ':$' + toRow;
}
let titleColName;
if (json.fromColumn !== null && json.fromColumn !== undefined) {
let fromColumn = json.fromColumn;
let toColumn;
if (json.toColumn !== null && json.toColumn !== undefined) {
toColumn = json.toColumn;
}
else {
toColumn = json.fromColumn;
}
titleColName = '$' + this.getColumnName(fromColumn) + ':$' + this.getColumnName(toColumn);
}
if (titleRowName !== undefined) {
printTitleName += (sheet.name + '!' + titleRowName);
}
if (titleColName !== undefined && titleRowName !== undefined) {
printTitleName += ',' + (sheet.name + '!' + titleColName);
}
else if (titleColName !== undefined) {
printTitleName += (sheet.name + '!' + titleColName);
}
if (printTitleName !== '') {
this.printTitles.set(sheet.index - 1, printTitleName);
}
}
/* tslint:disable:no-any */
parserFreezePanes(json, sheet) {
sheet.freezePanes = new FreezePane();
if (json.row !== null && json.row !== undefined) {
sheet.freezePanes.row = json.row;
}
else {
sheet.freezePanes.row = 0;
}
if (json.column !== null && json.column !== undefined) {
sheet.freezePanes.column = json.column;
}
else {
sheet.freezePanes.column = 0;
}
sheet.freezePanes.leftCell = this.getCellName(sheet.freezePanes.row + 1, sheet.freezePanes.column + 1);
}
/* tslint:disable:no-any */
parserColumns(json, sheet) {
let columnsLength = json.length;
sheet.columns = [];
for (let column = 0; column < columnsLength; column++) {
let col = new Column();
if (json[column].index !== null && json[column].index !== undefined) {
col.index = json[column].index;
}
else {
throw Error('Column index is missing.');
}
if (json[column].width !== null && json[column].width !== undefined) {
col.width = json[column].width;
}
sheet.columns.push(col);
}
}
/* tslint:disable:no-any */
parserRows(json, sheet) {
let rowsLength = json.length;
sheet.rows = new Rows();
let rowId = 0;
for (let r = 0; r < rowsLength; r++) {
let row = this.parserRow(json[r], rowId);
rowId = row.index;
sheet.rows.add(row);
}
this.insertMergedCellsStyle(sheet);
}
insertMergedCellsStyle(sheet) {
if (this.mergeCells.length > 0) {
this.mergedCellsStyle.forEach((value, key) => {
let row = sheet.rows.filter((item) => {
return item.index === value.y;
})[0];
if (!isNullOrUndefined(row)) {
let cell = row.cells.filter((item) => {
return item.index === value.x;
})[0];
if (!isNullOrUndefined(cell)) {
cell.styleIndex = value.styleIndex;
}
else {
let cells = row.cells.filter((item) => {
return item.index <= value.x;
});
let insertIndex = 0;
if (cells.length > 0) {
insertIndex = row.cells.indexOf(cells[cells.length - 1]) + 1;
}
row.cells.splice(insertIndex, 0, this.createCell(value, key));
}
}
else {
let rows = sheet.rows.filter((item) => {
return item.index <= value.y;
});
let rowToInsert = new Row();
rowToInsert.index = value.y;
rowToInsert.cells = new Cells();
rowToInsert.cells.add(this.createCell(value, key));
let insertIndex = 0;
if (rows.length > 0) {
insertIndex = sheet.rows.indexOf(rows[rows.length - 1]) + 1;
}
sheet.rows.splice(insertIndex, 0, rowToInsert);
}
});
}
}
createCell(value, key) {
let cellToInsert = new Cell();
cellToInsert.refName = key;
cellToInsert.index = value.x;
cellToInsert.cellStyle = new CellStyle();
cellToInsert.styleIndex = value.styleIndex;
return cellToInsert;
}
/* tslint:disable:no-any */
parserRow(json, rowIndex) {
let row = new Row();
//Row Height
if (json.height !== null && json.height !== undefined) {
row.height = json.height;
}
//Row index
if (json.index !== null && json.index !== undefined) {
row.index = json.index;
}
else {
throw Error('Row index is missing.');
}
if (json.grouping !== null && json.grouping !== undefined) {
this.parseGrouping(json.grouping, row);
}
this.parseCells(json.cells, row);
return row;
}
/* tslint:disable:no-any */
parseGrouping(json, row) {
row.grouping = new Grouping();
if (json.outlineLevel !== undefined) {
row.grouping.outlineLevel = json.outlineLevel;
}
if (json.isCollapsed !== undefined) {
row.grouping.isCollapsed = json.isCollapsed;
}
if (json.isHidden !== undefined) {
row.grouping.isHidden = json.isHidden;
}
}
/* tslint:disable:no-any */
parseCells(json, row) {
row.cells = new Cells();
let cellsLength = json !== undefined ? json.length : 0;
let spanMin = 1;
let spanMax = 1;
for (let cellId = 0; cellId < cellsLength; cellId++) {
/* tslint:disable:no-any */
let jsonCell = json[cellId];
let cell = new Cell();
//cell index
if (jsonCell.index !== null && jsonCell.index !== undefined) {
cell.index = jsonCell.index;
}
else {
throw Error('Cell index is missing.');
}
if (cell.index < spanMin) {
spanMin = cell.index;
}
else if (cell.index > spanMax) {
spanMax = cell.index;
}
//Update the Cell name
cell.refName = this.getCellName(row.index, cell.index);
//Row span
if (jsonCell.rowSpan !== null && jsonCell.rowSpan !== undefined) {
cell.rowSpan = jsonCell.rowSpan - 1;
}
else {
cell.rowSpan = 0;
}
//Column span
if (jsonCell.colSpan !== null && jsonCell.colSpan !== undefined) {
cell.colSpan = jsonCell.colSpan - 1;
}
else {
cell.colSpan = 0;
}
//Hyperlink
if (jsonCell.hyperlink !== null && jsonCell.hyperlink !== undefined) {
let hyperLink = new HyperLink();
if (jsonCell.hyperlink.target !== undefined) {
hyperLink.target = jsonCell.hyperlink.target;
if (jsonCell.hyperlink.displayText !== undefined) {
cell.value = jsonCell.hyperlink.displayText;
}
else {
cell.value = jsonCell.hyperlink.target;
}
cell.type = this.getCellValueType(cell.value);
hyperLink.ref = cell.refName;
hyperLink.rId = (this.mHyperLinks.length + 1);
this.mHyperLinks.push(hyperLink);
cell.cellStyle = new CellStyle();
/* tslint:disable-next-line:max-line-length */
this.parserCellStyle((jsonCell.style !== undefined ? this.mergeOptions(jsonCell.style, this.hyperlinkStyle) : this.hyperlinkStyle), cell.cellStyle, 'string');
cell.styleIndex = cell.cellStyle.index;
}
}
// formulas
if (jsonCell.formula !== null && jsonCell.formula !== undefined) {
cell.formula = jsonCell.formula;
cell.type = 'formula';
}
//Cell value
if (jsonCell.value !== null && jsonCell.value !== undefined) {
if (cell.formula !== undefined) {
cell.value = 0;
}
else {
cell.value = jsonCell.value;
cell.type = this.getCellValueType(cell.value);
}
}
if (jsonCell.style !== null && jsonCell.style !== undefined && cell.styleIndex === undefined) {
cell.cellStyle = new CellStyle();
if (cell.value instanceof Date) {
this.parserCellStyle(jsonCell.style, cell.cellStyle, cell.type, 14);
}
else {
this.parserCellStyle(jsonCell.style, cell.cellStyle, cell.type);
}
cell.styleIndex = cell.cellStyle.index;
}
else if (cell.value instanceof Date) {
cell.cellStyle = new CellStyle();
this.parserCellStyle({}, cell.cellStyle, cell.type, 14);
cell.styleIndex = cell.cellStyle.index;
}
this.parseCellType(cell);
this.mergeCells = this.processMergeCells(cell, row.index, this.mergeCells);
row.cells.add(cell);
}
row.spans = (spanMin) + ':' + (spanMax);
}
GetColors() {
let colors;
colors = new Map();
/* tslint:disable */
colors.set('WHITE', 'FFFFFFFF');
/* tslint:disable */
colors.set('SILVER', 'FFC0C0C0');
/* tslint:disable */
colors.set('GRAY', 'FF808080');
/* tslint:disable */
colors.set('BLACK', 'FF000000');
/* tslint:disable */
colors.set('RED', 'FFFF0000');
/* tslint:disable */
colors.set('MAROON', 'FF800000');
/* tslint:disable */
colors.set('YELLOW', 'FFFFFF00');
/* tslint:disable */
colors.set('OLIVE', 'FF808000');
/* tslint:disable */
colors.set('LIME', 'FF00FF00');
/* tslint:disable */
colors.set('GREEN', 'FF008000');
/* tslint:disable */
colors.set('AQUA', 'FF00FFFF');
/* tslint:disable */
colors.set('TEAL', 'FF008080');
/* tslint:disable */
colors.set('BLUE', 'FF0000FF');
/* tslint:disable */
colors.set('NAVY', 'FF000080');
/* tslint:disable */
colors.set('FUCHSIA', 'FFFF00FF');
/* tslint:disable */
colors.set('PURPLE', 'FF800080');
return colors;
}
processColor(colorVal) {
if (colorVal.indexOf('#') === 0) {
return colorVal.replace('#', 'FF');
}
colorVal = colorVal.toUpperCase();
this.rgbColors = this.GetColors();
if (this.rgbColors.has(colorVal)) {
colorVal = this.rgbColors.get(colorVal);
}
else {
colorVal = 'FF000000';
}
return colorVal;
}
processCellValue(value, cell) {
let cellValue = value;
if (value.indexOf("<font") !== -1 || value.indexOf("<a") !== -1 || value.indexOf("<b>") !== -1 ||
value.indexOf("<i>") !== -1 || value.indexOf("<u>") !== -1) {
let processedVal = '';
let startindex = value.indexOf('<', 0);
let endIndex = value.indexOf('>', startindex + 1);
if (startindex >= 0 && endIndex >= 0) {
if (startindex !== 0) {
processedVal += '<r><t xml:space="preserve">' + this.processString(value.substring(0, startindex)) + '</t></r>';
}
while (startindex >= 0 && endIndex >= 0) {
endIndex = value.indexOf('>', startindex + 1);
if (endIndex >= 0) {
let subString = value.substring(startindex + 1, endIndex);
startindex = value.indexOf('<', endIndex + 1);
if (startindex < 0) {
startindex = cellValue.length;
}
let text = cellValue.substring(endIndex + 1, startindex);
if (text.length !== 0) {
let subSplit = subString.split(' ');
if (subSplit.length > 0) {
processedVal += '<r><rPr>';
}
if (subSplit.length > 1) {
for (let element of subSplit) {
let start = element.trim().substring(0, 5);
switch (start) {
case 'size=':
processedVal += '<sz val="' + element.substring(6, element.length - 1) + '"/>';
break;
case 'face=':
processedVal += '<rFont val="' + element.substring(6, element.length - 1) + '"/>';
break;
case 'color':
processedVal += '<color rgb="' + this.processColor(element.substring(7, element.length - 1)) + '"/>';
break;
case 'href=':
let hyperLink = new HyperLink();
hyperLink.target = element.substring(6, element.length - 1).trim();
hyperLink.ref = cell.refName;
hyperLink.rId = (this.mHyperLinks.length + 1);
this.mHyperLinks.push(hyperLink);
processedVal += '<color rgb="FF0000FF"/><u/><b/>';
break;
}
}
}
else if (subSplit.length === 1) {
let style = subSplit[0].trim();
switch (style) {
case 'b':
processedVal += '<b/>';
break;
case 'i':
processedVal += '<i/>';
break;
case 'u':
processedVal += '<u/>';
break;
}
}
processedVal += '</rPr><t xml:space="preserve">' + this.processString(text) + '</t></r>';
}
}
}
if (processedVal === '') {
return cellValue;
}
return processedVal;
}
else {
return cellValue;
}
}
else {
return cellValue;
}
}
applyGlobalStyle(json, cellStyle) {
if (this.cellStyles.has(json.name)) {
cellStyle.index = this.mStyles.filter((a) => (a.name === json.name))[0].index;
cellStyle.name = json.name;
}
}
/* tslint:disable:no-any */
parserCellStyle(json, cellStyle, cellType, defStyleIndex) {
//name
if (json.name !== null && json.name !== undefined) {
if (cellStyle.isGlobalStyle) {
cellStyle.name = json.name;
}
else {
this.applyGlobalStyle(json, cellStyle);
return;
}
}
//background color
if (json.backColor !== null && json.backColor !== undefined) {
cellStyle.backColor = json.backColor;
}
//borders
//leftBorder
cellStyle.borders = new Borders();
//AllBorder
if (json.borders !== null && json.borders !== undefined) {
this.parserBorder(json.borders, cellStyle.borders.all);
}
//leftborder
if (json.leftBorder !== null && json.leftBorder !== undefined) {
this.parserBorder(json.leftBorder, cellStyle.borders.left);
}
//rightBorder
if (json.rightBorder !== null && json.rightBorder !== undefined) {
this.parserBorder(json.rightBorder, cellStyle.borders.right);
}
//topBorder
if (json.topBorder !== null && json.topBorder !== undefined) {
this.parserBorder(json.topBorder, cellStyle.borders.top);
}
//bottomBorder
if (json.bottomBorder !== null && json.bottomBorder !== undefined) {
this.parserBorder(json.bottomBorder, cellStyle.borders.bottom);
}
//fontName
if (json.fontName !== null && json.fontName !== undefined) {
cellStyle.fontName = json.fontName;
}
//fontSize
if (json.fontSize !== null && json.fontSize !== undefined) {
cellStyle.fontSize = json.fontSize;
}
//fontColor
if (json.fontColor !== null && json.fontColor !== undefined) {
cellStyle.fontColor = json.fontColor;
}
//italic
if (json.italic !== null && json.italic !== undefined) {
cellStyle.italic = json.italic;
}
//bold
if (json.bold !== null && json.bold !== undefined) {
cellStyle.bold = json.bold;
}
//hAlign
if (json.hAlign !== null && json.hAlign !== undefined) {
cellStyle.hAlign = json.hAlign.toLowerCase();
}
//indent
if (json.indent !== null && json.indent !== undefined) {
cellStyle.indent = json.indent;
if (!(cellStyle.hAlign === 'left' || cellStyle.hAlign === 'right')) {
cellStyle.hAlign = 'left';
}
}
if (json.rotation !== null && json.rotation !== undefined) {
cellStyle.rotation = json.rotation;
}
//vAlign
if (json.vAlign !== null && json.vAlign !== undefined) {
cellStyle.vAlign = json.vAlign.toLowerCase();
}
//underline
if (json.underline !== null && json.underline !== undefined) {
cellStyle.underline = json.underline;
}
//strikeThrough
if (json.strikeThrough !== null && json.strikeThrough !== undefined) {
cellStyle.strikeThrough = json.strikeThrough;
}
//wrapText
if (json.wrapText !== null && json.wrapText !== undefined) {
cellStyle.wrapText = json.wrapText;
}
//numberFormat
if (json.numberFormat !== null && json.numberFormat !== undefined) {
if (json.type !== null && json.type !== undefined) {
cellStyle.numberFormat = this.getNumberFormat(json.numberFormat, json.type);
}
else {
cellStyle.numberFormat = this.getNumberFormat(json.numberFormat, cellType);
}
}
else if (defStyleIndex !== undefined) {
cellStyle.numFmtId = 14;
cellStyle.numberFormat = 'GENERAL';
}
else {
cellStyle.numberFormat = 'GENERAL';
}
cellStyle.index = this.processCellStyle(cellStyle);
}
switchNumberFormat(numberFormat, type) {
let format = this.getNumberFormat(numberFormat, type);
if (format !== numberFormat) {
let numFmt = this.mNumFmt.get(numberFormat);
if (numFmt !== undefined) {
numFmt.formatCode = format;
if (this.mNumFmt.has(format)) {
for (let cellStyleXfs of this.mCellStyleXfs) {
if (cellStyleXfs.numFmtId === numFmt.numFmtId) {
cellStyleXfs.numFmtId = this.mNumFmt.get(format).numFmtId;
}
}
for (let cellXfs of this.mCellXfs) {
if (cellXfs.numFmtId === numFmt.numFmtId) {
cellXfs.numFmtId = this.mNumFmt.get(format).numFmtId;
}
}
}
}
}
}
changeNumberFormats(value) {
if (typeof value == "string") {
const regex = new RegExp(this.currency, 'g');
value = value.replace(regex, '[$' + this.currency + ']');
}
else if (typeof value == "object") {
for (var i = 0; i < value.length; i++) {
value[i] = value[i].replace(this.currency, '[$' + this.currency + ']');
}
}
return value;
}
getNumberFormat(numberFormat, type) {
let returnFormat;
switch (type) {
case 'number':
try {
returnFormat = this.intl.getNumberPattern({ format: numberFormat, currency: this.currency, useGrouping: true }, true);
if (this.currency.length > 1) {
returnFormat = this.changeNumberFormats(returnFormat);
}
}