Skip to content

Commit

Permalink
v3.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
leoreisdias committed Sep 4, 2023
1 parent eb4d176 commit a003354
Show file tree
Hide file tree
Showing 5 changed files with 314 additions and 151 deletions.
10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "excel-ent",
"version": "2.0.8",
"version": "3.0.0",
"license": "MIT",
"publishConfig": {
"access": "public"
Expand All @@ -16,14 +16,14 @@
"semantic-release": "semantic-release"
},
"dependencies": {
"csstype": "^3.0.11",
"ts-node": "^9.1.1"
"ts-node": "^9.1.1",
"xlsx-js-style": "^1.2.0"
},
"devDependencies": {
"@types/node": "^16.4.6",
"semantic-release": "^21.0.9",
"ts-node-dev": "^1.1.8",
"typescript": "^4.3.5",
"semantic-release": "^21.0.9"
"typescript": "^4.3.5"
},
"files": [
"lib/**/*"
Expand Down
190 changes: 190 additions & 0 deletions src/functions/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
import * as XLSX from 'xlsx-js-style';

import {
convertType,
downloadFile,
objectToSemicolons,
} from '../helpers/convert';
import {
ExportationType,
ExportMeExcelAdvancedProps,
ExportMeExcelOptions,
} from '../types';

const validateData = (data: any[], fileName: string) => {
if (
!Array.isArray(data) ||
typeof fileName !== 'string' ||
Object.prototype.toString.call(fileName) !== '[object String]'
) {
throw new Error(
'Invalid input types: First Params should be an Array and the second one a String',
);
}
};

const executeXLSX = (data: XLSX.CellObject[][], columnWidths?: number[]) => {
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.aoa_to_sheet(data);
ws['!cols'] = columnWidths?.map(width => ({ width }));
XLSX.utils.book_append_sheet(wb, ws);

return wb;
};

const exportFile = (
exportAs: ExportationType,
wb: XLSX.WorkBook,
fileName: string,
) => {
if (exportAs.type === 'base64') {
return XLSX.write(wb, { type: 'base64', bookType: 'xlsx' });
}

if (exportAs.type === 'buffer') {
return XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' });
}

if (exportAs.type === 'download') {
return XLSX.writeFile(wb, `${fileName}.xlsx`);
}

if (exportAs.type === 'filepath') {
return XLSX.writeFile(wb, exportAs.path);
}
};

export const exportmeExcelAdvanced = ({
fileName,
headers = [],
rows,
options,
exportAs,
}: ExportMeExcelAdvancedProps) => {
const {
bodyStyle = {},
columnWidths,
headerStyle = {},
sheetProps,
} = options ?? {};

const headerXLSX: XLSX.CellObject[] = headers.map(
cell =>
({
t: convertType(cell.type),
v: cell.value,
c: cell.comment?.map(comment => ({
a: comment.author,
t: comment.text,
})),
F: cell.formulaRange,
f: cell.formula,
l: cell.hyperlink && {
Target: cell.hyperlink?.target,
Tooltip: cell.hyperlink?.tooltip,
},
s: {
...(cell.style ?? {}),
...headerStyle,
},
z:
cell.type === 'number' || cell.type === 'date'
? cell.mask
: undefined,
w:
cell.type === 'number' || cell.type === 'date'
? cell.formatted
: undefined,
} as XLSX.CellObject),
);

const rowsXLSX: XLSX.CellObject[][] = rows.map(item =>
item.map(
cell =>
({
t: convertType(cell.type),
v: cell.value,
c: cell.comment?.map(comment => ({
t: comment.text,
a: comment.author,
})),
F: cell.formulaRange,
f: cell.formula,
l: cell.hyperlink && {
Target: cell.hyperlink.target,
Tooltip: cell.hyperlink.tooltip,
},
s: {
...(cell.style ?? {}),
...bodyStyle,
},
z:
cell.type === 'number' || cell.type === 'date'
? cell.mask
: undefined,
w:
cell.type === 'number' || cell.type === 'date'
? cell.formatted
: undefined,
} as XLSX.CellObject),
),
);

const wb = executeXLSX([headerXLSX, ...rowsXLSX], columnWidths);
wb.Props = sheetProps;

return exportFile(exportAs, wb, fileName);
};

export const exportmeExcel = (
data: Record<string, any>[],
fileName: string,
exportAs: ExportationType,
options?: ExportMeExcelOptions,
) => {
validateData(data, fileName);

const headers: XLSX.CellObject[] = Object.keys(data[0]).map(item => ({
v: item,
t: 's',
s: options?.headerStyle,
}));

const body: XLSX.CellObject[][] = data.map(item =>
Object.keys(item).map(key => ({
v: item[key],
t: 's',
s: options?.bodyStyle,
})),
);

const wb = executeXLSX([headers, ...body], options?.columnWidths);

wb.Props = options?.sheetProps;

return exportFile(exportAs, wb, fileName);
};

export const exportmeToCsv = (data: any[], fileName: string) => {
if (
typeof fileName !== 'string' ||
Object.prototype.toString.call(fileName) !== '[object String]'
) {
throw new Error(
'Invalid input types: First Params should be an Array and the second one a String',
);
}

if (window) {
const computedCSV = new Blob([objectToSemicolons(data)], {
type: 'text/csv;charset=utf-8',
});

const csvLink = window.URL.createObjectURL(computedCSV);
downloadFile(csvLink, `${fileName}.csv`);
} else {
throw new Error(
'Window is not definided: You must be using it in a browser',
);
}
};
43 changes: 43 additions & 0 deletions src/helpers/convert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
export const convertType = (
type: 'string' | 'number' | 'boolean' | 'date' | 'blank' | 'error',
) => {
switch (type) {
case 'string':
return 's';
case 'number':
return 'n';
case 'boolean':
return 'b';
case 'date':
return 'd';
case 'blank':
return 'z';
case 'error':
return 'e';
default:
return 's';
}
};

export function downloadFile(output: string, fileName: string) {
const link = document.createElement('a');
document.body.appendChild(link);
link.download = fileName;
link.href = output;
link.click();
}

export function objectToSemicolons(data: any[]) {
const colsHead = Object.keys(data[0])
.map(key => [key])
.join(';');
const colsData = data
.map(obj => [
Object.keys(obj)
.map(col => [obj[col]])
.join(';'),
])
.join('\n');

return `${colsHead}\n${colsData}`;
}
Loading

0 comments on commit a003354

Please sign in to comment.