Skip to content

Commit 3d7993a

Browse files
committed
feat: add downloadExcelJS()
1 parent 8d7fbdd commit 3d7993a

File tree

3 files changed

+53
-9
lines changed

3 files changed

+53
-9
lines changed

.prettierrc.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
{
2-
"semi": false,
2+
"semi": false
33
}

readme.md

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,34 @@ const excel = useExcelJS({
140140
})
141141
```
142142

143+
You can also use the non-hook function version which the `useExcelJS` uses internally.
144+
145+
```ts
146+
import { downloadExcelJS } from 'react-use-exceljs'
147+
148+
const onClick = () => {
149+
downloadExcelJS({
150+
filename: "testing.xlsx",
151+
data: [
152+
{id: 1},
153+
{id: 2}
154+
],
155+
worksheets: [
156+
{
157+
name: "Sheet 1",
158+
columns: [
159+
{
160+
header: "Id",
161+
key: "id",
162+
width: 10,
163+
},
164+
],
165+
},
166+
],
167+
})
168+
}
169+
```
170+
143171

144172
## Optimization
145-
The hook lazily imports `file-saver` and the rather large `exceljs` package only once the `download` function is executed.
173+
The `file-saver` and the rather large `exceljs` packages are lazily loaded on initiation of an excel download.

src/react-use-exceljs.ts

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,30 @@ export function useExcelJS<T extends Array<Sheet>>({
1313
}) {
1414
return {
1515
download: React.useCallback(
16-
async (data: Data<T>) => {
17-
const buffer = await makeBuffer({ worksheets, data, intercept })
18-
const fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
19-
const blob = new Blob([buffer], { type: fileType })
20-
const { default: {saveAs} } = await import("./deps")
21-
saveAs(blob, filename ?? "workbook.xlsx")
22-
},
16+
(data: Data<T>) =>
17+
downloadExcelJS({ filename, data, worksheets, intercept }),
2318
[filename, worksheets, intercept]
2419
),
2520
}
2621
}
22+
23+
async function downloadExcelJS<T extends Array<Sheet>>({
24+
filename,
25+
data,
26+
worksheets,
27+
intercept,
28+
}: {
29+
worksheets: T
30+
data: Data<T>
31+
filename?: Filename
32+
intercept?: InterceptFn
33+
}) {
34+
const buffer = await makeBuffer({ worksheets, data, intercept })
35+
const fileType =
36+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
37+
const blob = new Blob([buffer], { type: fileType })
38+
const {
39+
default: { saveAs },
40+
} = await import("./deps")
41+
saveAs(blob, filename ?? "workbook.xlsx")
42+
}

0 commit comments

Comments
 (0)