json-as-xlsx 2.6.0 → 2.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,9 +19,11 @@ You can see a live demo on any of these sites (there are several, just in case):
19
19
  ## Features
20
20
 
21
21
  - 📊 Turn an array of JSON sheets into a multi-sheet workbook.
22
+ - 🧱 Render several tables in the same sheet (opt-in, vertical or horizontal layout).
22
23
  - 🧭 Read deeply nested values (`"more.phone"`) or compute them with a function.
23
24
  - 🎨 Per-column number, date, currency and hyperlink formatting.
24
25
  - 🖌️ Opt-in cell styling for fonts, fills, borders, alignment and number formats.
26
+ - ⬜ Opt-in true blank cells for empty, null or missing values.
25
27
  - 📐 Automatic column widths (tunable with `extraLength`).
26
28
  - ↔️ Right-to-left (RTL) sheet support.
27
29
  - 🌐 Works in the browser (file download) and in Node.js (file or buffer output).
@@ -41,8 +43,9 @@ pnpm add json-as-xlsx
41
43
 
42
44
  ```js
43
45
  import xlsx from "json-as-xlsx"
44
- // or require
45
- let xlsx = require("json-as-xlsx")
46
+ // Alternative import styles:
47
+ // import { xlsx } from "json-as-xlsx"
48
+ // const xlsx = require("json-as-xlsx")
46
49
 
47
50
  let data = [
48
51
  {
@@ -78,6 +81,7 @@ let settings = {
78
81
  writeMode: "writeFile", // The available parameters are 'writeFile' and 'write'. This setting is optional. Useful in such cases https://docs.sheetjs.com/docs/solutions/output#example-remote-file
79
82
  writeOptions: {}, // Style options from https://docs.sheetjs.com/docs/api/write-options
80
83
  RTL: true, // Display the columns from right-to-left (the default value is false)
84
+ writeEmptyValuesAsBlankCells: false, // Set to true so Excel treats empty, null and missing values as blank cells
81
85
  }
82
86
 
83
87
  xlsx(data, settings) // Will download the excel file
@@ -93,6 +97,45 @@ xlsx(data, settings) // Will download the excel file
93
97
  | `writeMode` | `"writeFile"`/`"write"` | `"writeFile"` | `"writeFile"` downloads/writes the file; `"write"` returns the raw data (e.g. a Node buffer). |
94
98
  | `writeOptions` | `object` | `{}` | Passed straight to SheetJS — see [write options](https://docs.sheetjs.com/docs/api/write-options). |
95
99
  | `RTL` | `boolean` | `false` | Render every sheet right-to-left. |
100
+ | `writeEmptyValuesAsBlankCells` | `boolean` | `false` | Omit empty-string, `null`, `undefined` and missing-path values so Excel treats them as blank cells. |
101
+
102
+ ### True blank cells
103
+
104
+ For backward compatibility, empty values are written as empty strings by
105
+ default. Excel can count those cells as text values even when they look blank.
106
+ Set `writeEmptyValuesAsBlankCells: true` to omit empty-string, `null`,
107
+ `undefined` and missing-path values from the worksheet XML:
108
+
109
+ ```js
110
+ let data = [
111
+ {
112
+ sheet: "Sparse data",
113
+ columns: [
114
+ { label: "ID", value: "id" },
115
+ { label: "Email", value: (row) => row.contact?.email ?? "" },
116
+ { label: "Score", value: "score", format: "0.00" },
117
+ ],
118
+ content: [
119
+ { id: "ID-101", contact: { email: "ada@example.com" }, score: 98.5 },
120
+ { id: "ID-102", contact: { email: "" } },
121
+ { id: "ID-103", score: null },
122
+ { id: "ID-104" },
123
+ ],
124
+ },
125
+ ]
126
+
127
+ xlsx(data, {
128
+ fileName: "BlankCellSpreadsheet",
129
+ writeEmptyValuesAsBlankCells: true,
130
+ })
131
+ ```
132
+
133
+ Values like `0` and `false` are still written normally.
134
+
135
+ This option applies to both string-path columns (`value: "email"`) and function
136
+ columns (`value: (row) => row.email ?? ""`). Formats, hyperlinks and cell styles
137
+ are applied only to cells that still have a value; blank cells remain truly
138
+ blank. Sheets or multi-table entries with no content still render their headers.
96
139
 
97
140
  ### Callback
98
141
 
@@ -233,13 +276,67 @@ Supported style groups are `alignment`, `border`, `fill`, `font`, and `numFmt`.
233
276
  Column `format` values are also preserved as number formats when styles are
234
277
  enabled.
235
278
 
279
+ ### Multiple tables per sheet
280
+
281
+ By default a sheet renders a single table from its `columns` and `content`. To
282
+ place **several independent tables in the same sheet**, provide a `tables` array
283
+ instead — each entry has its own `columns` and `content` (with the same
284
+ formatting and styling options). This is fully opt-in: sheets that don't set
285
+ `tables` keep working exactly as before.
286
+
287
+ ```js
288
+ let data = [
289
+ {
290
+ sheet: "Quarter summary",
291
+ tablesLayout: "vertical", // "vertical" (default) stacks tables; "horizontal" places them side by side
292
+ tablesGap: 1, // blank rows (vertical) or columns (horizontal) between tables — defaults to 1
293
+ tables: [
294
+ {
295
+ columns: [
296
+ { label: "Product", value: "product" },
297
+ { label: "Revenue", value: "revenue", format: "$#,##0.00" },
298
+ ],
299
+ content: [
300
+ { product: "Keyboard", revenue: 35988 },
301
+ { product: "Monitor", revenue: 67830 },
302
+ ],
303
+ },
304
+ {
305
+ columns: [
306
+ { label: "Team", value: "team" },
307
+ { label: "Expenses", value: "expenses", format: "$#,##0.00" },
308
+ ],
309
+ content: [
310
+ { team: "Engineering", expenses: 42000 },
311
+ { team: "Marketing", expenses: 18500 },
312
+ ],
313
+ },
314
+ ],
315
+ },
316
+ ]
317
+
318
+ xlsx(data, { fileName: "MultiTableSpreadsheet" })
319
+ ```
320
+
321
+ When `tables` is present and non-empty it takes precedence over the sheet's
322
+ top-level `columns`/`content`.
323
+
324
+ | Sheet option | Type | Default | Description |
325
+ | --------------- | ---------------------------- | ------------ | ------------------------------------------------------------------------ |
326
+ | `tables` | `{ columns, content }[]` | — | Render multiple tables in the sheet. Each table keeps its own formatting. |
327
+ | `tablesLayout` | `"vertical"`/`"horizontal"` | `"vertical"` | Stack tables top-to-bottom or place them left-to-right. |
328
+ | `tablesGap` | `number` | `1` | Blank rows (vertical) or columns (horizontal) left between tables. |
329
+
236
330
  ## TypeScript
237
331
 
238
332
  The package is written in TypeScript and ships its own type definitions. The
239
- public interfaces are exported for your convenience:
333
+ public interfaces are exported for your convenience. The `xlsx` function is
334
+ available as both the default export and a named export:
240
335
 
241
336
  ```ts
242
337
  import xlsx, { IJsonSheet, ISettings, IColumn, IContent, ICellStyle } from "json-as-xlsx"
338
+ // or:
339
+ // import { xlsx, IJsonSheet, ISettings, IColumn, IContent, ICellStyle } from "json-as-xlsx"
243
340
 
244
341
  const data: IJsonSheet[] = [
245
342
  /* ... */
@@ -253,8 +350,8 @@ xlsx(data, settings)
253
350
 
254
351
  ## Examples
255
352
 
256
- These are the files used during development when copying them, change the
257
- imports from `../../src/index` to `json-as-xlsx`.
353
+ These examples are part of the Yarn workspace and are intended to be installed
354
+ and run from the repository root.
258
355
 
259
356
  - [Express with TypeScript](https://github.com/LuisEnMarroquin/json-as-xlsx/blob/main/packages/demo-express)
260
357
  - [ReactJS with TypeScript](https://github.com/LuisEnMarroquin/json-as-xlsx/blob/main/packages/demo-reactjs)
package/dist/index.d.ts CHANGED
@@ -12,11 +12,18 @@ export type IContentValue = string | number | boolean | Date | IContent | IStyle
12
12
  export interface IContent {
13
13
  [key: string]: IContentValue;
14
14
  }
15
- export interface IJsonSheet {
16
- sheet?: string;
15
+ export interface IJsonSheetTable {
17
16
  columns: IColumn[];
18
17
  content: IContent[];
19
18
  }
19
+ export interface IJsonSheet {
20
+ sheet?: string;
21
+ columns?: IColumn[];
22
+ content?: IContent[];
23
+ tables?: IJsonSheetTable[];
24
+ tablesLayout?: "vertical" | "horizontal";
25
+ tablesGap?: number;
26
+ }
20
27
  export interface ISettings {
21
28
  enableStyles?: boolean;
22
29
  extraLength?: number;
@@ -24,6 +31,10 @@ export interface ISettings {
24
31
  writeOptions?: WritingOptions;
25
32
  writeMode?: string;
26
33
  RTL?: boolean;
34
+ writeEmptyValuesAsBlankCells?: boolean;
35
+ }
36
+ export interface IEmptyCellOptions {
37
+ writeEmptyValuesAsBlankCells?: boolean;
27
38
  }
28
39
  export interface IJsonSheetRow {
29
40
  [key: string]: IContentValue;
@@ -33,8 +44,12 @@ export interface IWorksheetColumnWidth {
33
44
  }
34
45
  export type IWorkbookCallback = (workbook: WorkBook) => void;
35
46
  export { utils, WorkBook, WorkSheet };
36
- export declare const getContentProperty: (content: IContent, property: string) => string | number | boolean | Date | IContent | IStyledCell;
37
- export declare const getJsonSheetRow: (content: IContent, columns: IColumn[]) => IJsonSheetRow;
47
+ export declare function getContentProperty(content: IContent, property: string): Exclude<IContentValue, null>;
48
+ export declare function getContentProperty(content: IContent, property: string, options: IEmptyCellOptions & {
49
+ writeEmptyValuesAsBlankCells: true;
50
+ }): IContentValue;
51
+ export declare function getContentProperty(content: IContent, property: string, options: IEmptyCellOptions): IContentValue;
52
+ export declare const getJsonSheetRow: (content: IContent, columns: IColumn[], options?: IEmptyCellOptions) => IJsonSheetRow;
38
53
  export declare const getWorksheetColumnWidths: (worksheet: WorkSheet, extraLength?: number) => IWorksheetColumnWidth[];
39
54
  export declare function xlsx(jsonSheets: IJsonSheet[], settings: ISettings & {
40
55
  writeMode: "write";
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.libraryName=exports.getWorksheetColumnWidths=exports.getJsonSheetRow=exports.getContentProperty=exports.utils=void 0;exports.xlsx=xlsx;const xlsx_1=require("@e965/xlsx");Object.defineProperty(exports,"utils",{enumerable:true,get:function(){return xlsx_1.utils}});const styles_1=require("./styles");const getContentProperty=(content,property)=>{const accessContentProperties=(content,properties)=>{const value=content[properties[0]];if(properties.length===1){return value!==null&&value!==void 0?value:""}if(value===undefined||value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"||value instanceof Date){return""}return accessContentProperties(value,properties.slice(1))};const properties=property.split(".");return accessContentProperties(content,properties)};exports.getContentProperty=getContentProperty;const getJsonSheetRow=(content,columns)=>{const jsonSheetRow={};columns.forEach(column=>{if(typeof column.value==="function"){jsonSheetRow[column.label]=column.value(content)}else{jsonSheetRow[column.label]=(0,exports.getContentProperty)(content,column.value)}});return jsonSheetRow};exports.getJsonSheetRow=getJsonSheetRow;const applyColumnFormat=(worksheet,columnIds,columnFormats)=>{var _a;for(let i=0;i<columnIds.length;i+=1){const columnFormat=columnFormats[i];if(!columnFormat){continue}const column=xlsx_1.utils.decode_col(columnIds[i]);const range=xlsx_1.utils.decode_range((_a=worksheet["!ref"])!==null&&_a!==void 0?_a:"");for(let row=range.s.r+1;row<=range.e.r;++row){const ref=xlsx_1.utils.encode_cell({r:row,c:column});if(worksheet[ref]){switch(columnFormat){case"hyperlink":worksheet[ref].l={Target:worksheet[ref].v};break;default:worksheet[ref].z=columnFormat}}}}};const applyHeaderStyles=(worksheet,columnIds,headerStyles)=>{for(let i=0;i<columnIds.length;i+=1){const headerStyle=headerStyles[i];if(!headerStyle){continue}const column=xlsx_1.utils.decode_col(columnIds[i]);const ref=xlsx_1.utils.encode_cell({r:0,c:column});if(worksheet[ref]){applyCellStyles(worksheet[ref],headerStyle)}}};const applyColumnStyles=(worksheet,columnIds,columnStyles)=>{var _a;for(let i=0;i<columnIds.length;i+=1){const columnStyle=columnStyles[i];if(!columnStyle){continue}const column=xlsx_1.utils.decode_col(columnIds[i]);const range=xlsx_1.utils.decode_range((_a=worksheet["!ref"])!==null&&_a!==void 0?_a:"");for(let row=range.s.r+1;row<=range.e.r;++row){const ref=xlsx_1.utils.encode_cell({r:row,c:column});if(worksheet[ref]){applyCellStyles(worksheet[ref],columnStyle)}}}};const getWorksheetColumnIds=worksheet=>{var _a;const columnRange=xlsx_1.utils.decode_range((_a=worksheet["!ref"])!==null&&_a!==void 0?_a:"");const columnIds=[];for(let C=columnRange.s.c;C<=columnRange.e.c;C++){const address=xlsx_1.utils.encode_col(C);columnIds.push(address)}return columnIds};const getObjectLength=object=>{if(isStyledCell(object)){return getObjectLength(object.v)}if(typeof object==="string"){return Math.max(...object.split("\n").map(string=>string.length))}if(typeof object==="number"){return object.toString().length}if(typeof object==="boolean"){return object?"true".length:"false".length}if(object instanceof Date){return object.toString().length}return 0};const getWorksheetColumnWidths=(worksheet,extraLength=1)=>{const columnLetters=getWorksheetColumnIds(worksheet);return columnLetters.map(column=>{const columnCells=Object.keys(worksheet).filter(cell=>{return cell.replace(/[0-9]/g,"")===column});const maxWidthCell=columnCells.reduce((maxWidth,cellId)=>{const cell=worksheet[cellId];const cellContentLength=getObjectLength(cell.v);if(!cell.z){return Math.max(maxWidth,cellContentLength)}const cellFormatLength=cell.z.length;const largestWidth=Math.max(cellContentLength,cellFormatLength);return Math.max(maxWidth,largestWidth)},0);return{width:maxWidthCell+extraLength}})};exports.getWorksheetColumnWidths=getWorksheetColumnWidths;const getWorksheet=(jsonSheet,settings)=>{let jsonSheetRows;if(jsonSheet.content.length>0){jsonSheetRows=jsonSheet.content.map(contentItem=>{return(0,exports.getJsonSheetRow)(contentItem,jsonSheet.columns)})}else{jsonSheetRows=jsonSheet.columns.map(column=>({[column.label]:""}))}const worksheet=xlsx_1.utils.json_to_sheet(jsonSheetRows);const worksheetColumnIds=getWorksheetColumnIds(worksheet);const worksheetColumnFormats=jsonSheet.columns.map(jsonSheetColumn=>{var _a;return(_a=jsonSheetColumn.format)!==null&&_a!==void 0?_a:null});applyColumnFormat(worksheet,worksheetColumnIds,worksheetColumnFormats);if(settings.enableStyles){const worksheetHeaderStyles=jsonSheet.columns.map(jsonSheetColumn=>{var _a;return(_a=jsonSheetColumn.headerStyle)!==null&&_a!==void 0?_a:null});const worksheetColumnStyles=jsonSheet.columns.map(jsonSheetColumn=>{var _a;return(_a=jsonSheetColumn.cellStyle)!==null&&_a!==void 0?_a:null});applyHeaderStyles(worksheet,worksheetColumnIds,worksheetHeaderStyles);applyColumnStyles(worksheet,worksheetColumnIds,worksheetColumnStyles)}worksheet["!cols"]=(0,exports.getWorksheetColumnWidths)(worksheet,settings.extraLength);return worksheet};const applyCellStyles=(cell,...styles)=>{const existingStyle=(0,styles_1.isCellStyleObject)(cell.s)?cell.s:undefined;const mergedStyle=(0,styles_1.mergeCellStyles)(...styles,existingStyle);if(Object.keys(mergedStyle).length>0){cell.s=mergedStyle}};const validCellTypes=new Set(["b","n","e","s","d","z","str"]);const styleKeys=new Set(["alignment","border","fill","font","numFmt"]);const hasStyleKeys=style=>{return(0,styles_1.isCellStyleObject)(style)&&Object.keys(style).some(key=>styleKeys.has(key))};const isCellLink=value=>{return Boolean(value)&&typeof value==="object"&&!Array.isArray(value)&&typeof value.Target==="string"};const isStyledCell=value=>{if(!value||typeof value!=="object"||Array.isArray(value)){return false}const cell=value;return"v"in cell&&(validCellTypes.has(String(cell.t))||hasStyleKeys(cell.s)||typeof cell.z==="string"||isCellLink(cell.l))};const writeWorkbook=(workbook,settings={})=>{var _a,_b,_c,_d,_e,_f;var _g;const RTL=Boolean(settings.RTL);(_a=workbook.Workbook)!==null&&_a!==void 0?_a:workbook.Workbook={};(_b=(_g=workbook.Workbook).Views)!==null&&_b!==void 0?_b:_g.Views=[{}];workbook.Workbook.Views.forEach(view=>{view.RTL=RTL});const filename=`${(_c=settings.fileName)!==null&&_c!==void 0?_c:"Spreadsheet"}.xlsx`;const writeOptions=(_d=settings.writeOptions)!==null&&_d!==void 0?_d:{};const writeType=(_e=writeOptions.type)!==null&&_e!==void 0?_e:"buffer";if(settings.enableStyles){const bookType=(_f=writeOptions.bookType)!==null&&_f!==void 0?_f:"xlsx";if(bookType!=="xlsx"){throw new Error("enableStyles only supports the xlsx book type")}const rawWorkbook=(0,xlsx_1.write)(workbook,Object.assign(Object.assign({},writeOptions),{bookType:bookType,type:"array"}));const styledWorkbook=(0,styles_1.patchStyledWorkbook)(workbook,rawWorkbook);if(settings.writeMode==="write"){return(0,styles_1.toStyledOutput)(styledWorkbook,writeType)}else if(settings.writeMode==="writeFile"){(0,styles_1.saveXlsxOutput)(styledWorkbook,filename);return}else if(writeOptions.type==="buffer"){return(0,styles_1.toStyledOutput)(styledWorkbook,writeOptions.type)}else{(0,styles_1.saveXlsxOutput)(styledWorkbook,filename);return}}if(settings.writeMode==="write"){return(0,xlsx_1.write)(workbook,Object.assign(Object.assign({},writeOptions),{type:writeType}))}else if(settings.writeMode==="writeFile"){(0,xlsx_1.writeFile)(workbook,filename,writeOptions);return}else if(writeOptions.type==="buffer"){return(0,xlsx_1.write)(workbook,writeOptions)}else{(0,xlsx_1.writeFile)(workbook,filename,writeOptions);return}};function xlsx(jsonSheets,settings={},workbookCallback=()=>{}){if(jsonSheets.length===0)return;const workbook=xlsx_1.utils.book_new();jsonSheets.forEach((actualSheet,actualIndex)=>{var _a;const worksheet=getWorksheet(actualSheet,settings);const worksheetName=(_a=actualSheet.sheet)!==null&&_a!==void 0?_a:`Sheet ${actualIndex+1}`;xlsx_1.utils.book_append_sheet(workbook,worksheet,worksheetName)});workbookCallback(workbook);return writeWorkbook(workbook,settings)}exports.default=xlsx;exports.libraryName="json-as-xlsx";module.exports=xlsx;module.exports.getContentProperty=exports.getContentProperty;module.exports.getJsonSheetRow=exports.getJsonSheetRow;module.exports.getWorksheetColumnWidths=exports.getWorksheetColumnWidths;module.exports.utils=xlsx_1.utils;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.libraryName=exports.getWorksheetColumnWidths=exports.getJsonSheetRow=exports.utils=void 0;exports.getContentProperty=getContentProperty;exports.xlsx=xlsx;const xlsx_1=require("@e965/xlsx");Object.defineProperty(exports,"utils",{enumerable:true,get:function(){return xlsx_1.utils}});const styles_1=require("./styles");const normalizeEmptyCellValue=(value,options={})=>{if(options.writeEmptyValuesAsBlankCells&&(value===undefined||value===null||value==="")){return null}if(options.writeEmptyValuesAsBlankCells&&isStyledCell(value)){const styledValue=value.v;if(styledValue===undefined||styledValue===null||styledValue===""){return null}}return value!==null&&value!==void 0?value:""};function getContentProperty(content,property,options={}){const accessContentProperties=(content,properties)=>{const value=content[properties[0]];if(properties.length===1){return normalizeEmptyCellValue(value,options)}if(value===undefined||value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"||value instanceof Date){return normalizeEmptyCellValue(undefined,options)}return accessContentProperties(value,properties.slice(1))};const properties=property.split(".");return accessContentProperties(content,properties)}const getJsonSheetRow=(content,columns,options={})=>{const jsonSheetRow={};columns.forEach(column=>{if(typeof column.value==="function"){jsonSheetRow[column.label]=normalizeEmptyCellValue(column.value(content),options)}else{jsonSheetRow[column.label]=getContentProperty(content,column.value,options)}});return jsonSheetRow};exports.getJsonSheetRow=getJsonSheetRow;const applyColumnFormat=(worksheet,table,columnFormats)=>{for(let i=0;i<columnFormats.length;i+=1){const columnFormat=columnFormats[i];if(!columnFormat){continue}const column=table.startCol+i;for(let row=table.startRow+1;row<=table.startRow+table.dataRowCount;++row){const ref=xlsx_1.utils.encode_cell({r:row,c:column});if(worksheet[ref]&&!isBlankWorksheetCell(worksheet[ref])){switch(columnFormat){case"hyperlink":worksheet[ref].l={Target:worksheet[ref].v};break;default:worksheet[ref].z=columnFormat}}}}};const applyHeaderStyles=(worksheet,table,headerStyles)=>{for(let i=0;i<headerStyles.length;i+=1){const headerStyle=headerStyles[i];if(!headerStyle){continue}const column=table.startCol+i;const ref=xlsx_1.utils.encode_cell({r:table.startRow,c:column});if(worksheet[ref]){applyCellStyles(worksheet[ref],headerStyle)}}};const applyColumnStyles=(worksheet,table,columnStyles)=>{for(let i=0;i<columnStyles.length;i+=1){const columnStyle=columnStyles[i];if(!columnStyle){continue}const column=table.startCol+i;for(let row=table.startRow+1;row<=table.startRow+table.dataRowCount;++row){const ref=xlsx_1.utils.encode_cell({r:row,c:column});if(worksheet[ref]&&!isBlankWorksheetCell(worksheet[ref])){applyCellStyles(worksheet[ref],columnStyle)}}}};const getWorksheetColumnIds=worksheet=>{var _a;const columnRange=xlsx_1.utils.decode_range((_a=worksheet["!ref"])!==null&&_a!==void 0?_a:"");const columnIds=[];for(let C=columnRange.s.c;C<=columnRange.e.c;C++){const address=xlsx_1.utils.encode_col(C);columnIds.push(address)}return columnIds};const getObjectLength=object=>{if(isStyledCell(object)){return getObjectLength(object.v)}if(typeof object==="string"){return Math.max(...object.split("\n").map(string=>string.length))}if(typeof object==="number"){return object.toString().length}if(typeof object==="boolean"){return object?"true".length:"false".length}if(object instanceof Date){return object.toString().length}return 0};const isBlankWorksheetCell=cell=>{return cell.t==="z"||cell.v===null||cell.v===undefined};const getWorksheetColumnWidths=(worksheet,extraLength=1)=>{const columnLetters=getWorksheetColumnIds(worksheet);return columnLetters.map(column=>{const columnCells=Object.keys(worksheet).filter(cell=>{return cell.replace(/[0-9]/g,"")===column});const maxWidthCell=columnCells.reduce((maxWidth,cellId)=>{const cell=worksheet[cellId];const cellContentLength=getObjectLength(cell.v);if(!cell.z){return Math.max(maxWidth,cellContentLength)}const cellFormatLength=cell.z.length;const largestWidth=Math.max(cellContentLength,cellFormatLength);return Math.max(maxWidth,largestWidth)},0);return{width:maxWidthCell+extraLength}})};exports.getWorksheetColumnWidths=getWorksheetColumnWidths;const buildJsonSheetRows=(columns,content,settings)=>{if(content.length>0){return content.map(contentItem=>(0,exports.getJsonSheetRow)(contentItem,columns,settings))}if(settings.writeEmptyValuesAsBlankCells){return[]}return columns.map(column=>({[column.label]:""}))};const getWorksheet=(jsonSheet,settings)=>{var _a,_b,_c,_d;const tables=jsonSheet.tables&&jsonSheet.tables.length>0?jsonSheet.tables:[{columns:(_a=jsonSheet.columns)!==null&&_a!==void 0?_a:[],content:(_b=jsonSheet.content)!==null&&_b!==void 0?_b:[]}];const layout=(_c=jsonSheet.tablesLayout)!==null&&_c!==void 0?_c:"vertical";const gap=(_d=jsonSheet.tablesGap)!==null&&_d!==void 0?_d:1;let worksheet;let nextRow=0;let nextCol=0;const placedTables=[];tables.forEach(table=>{const jsonSheetRows=buildJsonSheetRows(table.columns,table.content,settings);const jsonSheetOptions=table.content.length===0&&settings.writeEmptyValuesAsBlankCells?{header:table.columns.map(column=>column.label)}:{};const startRow=nextRow;const startCol=nextCol;if(!worksheet){worksheet=xlsx_1.utils.json_to_sheet(jsonSheetRows,jsonSheetOptions)}else{xlsx_1.utils.sheet_add_json(worksheet,jsonSheetRows,Object.assign(Object.assign({},jsonSheetOptions),{origin:{r:startRow,c:startCol}}))}placedTables.push({columns:table.columns,startRow:startRow,startCol:startCol,dataRowCount:jsonSheetRows.length});if(layout==="horizontal"){nextCol=startCol+table.columns.length+gap}else{nextRow=startRow+1+jsonSheetRows.length+gap}});const builtWorksheet=worksheet;placedTables.forEach(placedTable=>{const tableColumnFormats=placedTable.columns.map(tableColumn=>{var _a;return(_a=tableColumn.format)!==null&&_a!==void 0?_a:null});applyColumnFormat(builtWorksheet,placedTable,tableColumnFormats);if(settings.enableStyles){const tableHeaderStyles=placedTable.columns.map(tableColumn=>{var _a;return(_a=tableColumn.headerStyle)!==null&&_a!==void 0?_a:null});const tableColumnStyles=placedTable.columns.map(tableColumn=>{var _a;return(_a=tableColumn.cellStyle)!==null&&_a!==void 0?_a:null});applyHeaderStyles(builtWorksheet,placedTable,tableHeaderStyles);applyColumnStyles(builtWorksheet,placedTable,tableColumnStyles)}});builtWorksheet["!cols"]=(0,exports.getWorksheetColumnWidths)(builtWorksheet,settings.extraLength);return builtWorksheet};const applyCellStyles=(cell,...styles)=>{const existingStyle=(0,styles_1.isCellStyleObject)(cell.s)?cell.s:undefined;const mergedStyle=(0,styles_1.mergeCellStyles)(...styles,existingStyle);if(Object.keys(mergedStyle).length>0){cell.s=mergedStyle}};const validCellTypes=new Set(["b","n","e","s","d","z","str"]);const styleKeys=new Set(["alignment","border","fill","font","numFmt"]);const hasStyleKeys=style=>{return(0,styles_1.isCellStyleObject)(style)&&Object.keys(style).some(key=>styleKeys.has(key))};const isCellLink=value=>{return Boolean(value)&&typeof value==="object"&&!Array.isArray(value)&&typeof value.Target==="string"};const isStyledCell=value=>{if(!value||typeof value!=="object"||Array.isArray(value)){return false}const cell=value;return"v"in cell&&(validCellTypes.has(String(cell.t))||hasStyleKeys(cell.s)||typeof cell.z==="string"||isCellLink(cell.l))};const writeWorkbook=(workbook,settings={})=>{var _a,_b,_c,_d,_e,_f;var _g;const RTL=Boolean(settings.RTL);(_a=workbook.Workbook)!==null&&_a!==void 0?_a:workbook.Workbook={};(_b=(_g=workbook.Workbook).Views)!==null&&_b!==void 0?_b:_g.Views=[{}];workbook.Workbook.Views.forEach(view=>{view.RTL=RTL});const filename=`${(_c=settings.fileName)!==null&&_c!==void 0?_c:"Spreadsheet"}.xlsx`;const writeOptions=(_d=settings.writeOptions)!==null&&_d!==void 0?_d:{};const writeType=(_e=writeOptions.type)!==null&&_e!==void 0?_e:"buffer";if(settings.enableStyles){const bookType=(_f=writeOptions.bookType)!==null&&_f!==void 0?_f:"xlsx";if(bookType!=="xlsx"){throw new Error("enableStyles only supports the xlsx book type")}const rawWorkbook=(0,xlsx_1.write)(workbook,Object.assign(Object.assign({},writeOptions),{bookType:bookType,type:"array"}));const styledWorkbook=(0,styles_1.patchStyledWorkbook)(workbook,rawWorkbook);if(settings.writeMode==="write"){return(0,styles_1.toStyledOutput)(styledWorkbook,writeType)}else if(settings.writeMode==="writeFile"){(0,styles_1.saveXlsxOutput)(styledWorkbook,filename);return}else if(writeOptions.type==="buffer"){return(0,styles_1.toStyledOutput)(styledWorkbook,writeOptions.type)}else{(0,styles_1.saveXlsxOutput)(styledWorkbook,filename);return}}if(settings.writeMode==="write"){return(0,xlsx_1.write)(workbook,Object.assign(Object.assign({},writeOptions),{type:writeType}))}else if(settings.writeMode==="writeFile"){(0,xlsx_1.writeFile)(workbook,filename,writeOptions);return}else if(writeOptions.type==="buffer"){return(0,xlsx_1.write)(workbook,writeOptions)}else{(0,xlsx_1.writeFile)(workbook,filename,writeOptions);return}};function xlsx(jsonSheets,settings={},workbookCallback=()=>{}){if(jsonSheets.length===0)return;const workbook=xlsx_1.utils.book_new();jsonSheets.forEach((actualSheet,actualIndex)=>{var _a;const worksheet=getWorksheet(actualSheet,settings);const worksheetName=(_a=actualSheet.sheet)!==null&&_a!==void 0?_a:`Sheet ${actualIndex+1}`;xlsx_1.utils.book_append_sheet(workbook,worksheet,worksheetName)});workbookCallback(workbook);return writeWorkbook(workbook,settings)}exports.default=xlsx;exports.libraryName="json-as-xlsx";module.exports=xlsx;module.exports.xlsx=xlsx;module.exports.default=xlsx;module.exports.libraryName=exports.libraryName;module.exports.getContentProperty=getContentProperty;module.exports.getJsonSheetRow=exports.getJsonSheetRow;module.exports.getWorksheetColumnWidths=exports.getWorksheetColumnWidths;module.exports.utils=xlsx_1.utils;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "json-as-xlsx",
3
- "version": "2.6.0",
3
+ "version": "2.6.2",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -33,7 +33,7 @@
33
33
  ],
34
34
  "repository": {
35
35
  "type": "git",
36
- "url": "https://github.com/LuisEnMarroquin/json-as-xlsx.git"
36
+ "url": "git+https://github.com/LuisEnMarroquin/json-as-xlsx.git"
37
37
  },
38
38
  "bugs": {
39
39
  "url": "https://github.com/LuisEnMarroquin/json-as-xlsx/issues"