diff --git a/.prettierrc.json b/.prettierrc.json index ddcc4ca..cce9d3c 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,3 +1,3 @@ { - "semi": false, + "semi": false } diff --git a/readme.md b/readme.md index 621f1f9..2efb05d 100644 --- a/readme.md +++ b/readme.md @@ -140,6 +140,34 @@ const excel = useExcelJS({ }) ``` +You can also use the non-hook function version which the `useExcelJS` uses internally. + +```ts +import { downloadExcelJS } from 'react-use-exceljs' + +const onClick = () => { + downloadExcelJS({ + filename: "testing.xlsx", + data: [ + {id: 1}, + {id: 2} + ], + worksheets: [ + { + name: "Sheet 1", + columns: [ + { + header: "Id", + key: "id", + width: 10, + }, + ], + }, + ], + }) +} +``` + ## Optimization -The hook lazily imports `file-saver` and the rather large `exceljs` package only once the `download` function is executed. +The `file-saver` and the rather large `exceljs` packages are lazily loaded on initiation of an excel download. diff --git a/src/react-use-exceljs.ts b/src/react-use-exceljs.ts index c3f6b9e..fe7d46b 100644 --- a/src/react-use-exceljs.ts +++ b/src/react-use-exceljs.ts @@ -13,14 +13,30 @@ export function useExcelJS>({ }) { return { download: React.useCallback( - async (data: Data) => { - const buffer = await makeBuffer({ worksheets, data, intercept }) - const fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" - const blob = new Blob([buffer], { type: fileType }) - const { default: {saveAs} } = await import("./deps") - saveAs(blob, filename ?? "workbook.xlsx") - }, + (data: Data) => + downloadExcelJS({ filename, data, worksheets, intercept }), [filename, worksheets, intercept] ), } } + +async function downloadExcelJS>({ + filename, + data, + worksheets, + intercept, +}: { + worksheets: T + data: Data + filename?: Filename + intercept?: InterceptFn +}) { + const buffer = await makeBuffer({ worksheets, data, intercept }) + const fileType = + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + const blob = new Blob([buffer], { type: fileType }) + const { + default: { saveAs }, + } = await import("./deps") + saveAs(blob, filename ?? "workbook.xlsx") +}