Skip to content

Commit

Permalink
feat: add downloadExcelJS()
Browse files Browse the repository at this point in the history
  • Loading branch information
dadamssg committed Apr 5, 2023
1 parent 8d7fbdd commit 3d7993a
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 9 deletions.
2 changes: 1 addition & 1 deletion .prettierrc.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"semi": false,
"semi": false
}
30 changes: 29 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
30 changes: 23 additions & 7 deletions src/react-use-exceljs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,30 @@ export function useExcelJS<T extends Array<Sheet>>({
}) {
return {
download: React.useCallback(
async (data: Data<T>) => {
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<T>) =>
downloadExcelJS({ filename, data, worksheets, intercept }),
[filename, worksheets, intercept]
),
}
}

async function downloadExcelJS<T extends Array<Sheet>>({
filename,
data,
worksheets,
intercept,
}: {
worksheets: T
data: Data<T>
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")
}

0 comments on commit 3d7993a

Please sign in to comment.