-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext_export.go
More file actions
78 lines (70 loc) · 2.51 KB
/
context_export.go
File metadata and controls
78 lines (70 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Package gin 提供基于 Gin 的增强上下文与相关组件。
package gin
import (
"fmt"
"io"
"net/http"
"github.com/darkit/gin/pkg/export"
)
// ExportExcel 导出 Excel 文件,filename 为空时使用默认名称。
func (c *Context) ExportExcel(data any, filename string, opts ...export.ExcelOption) error {
content, err := export.ExportExcel(data, opts...)
if err != nil {
return err
}
return c.writeDownload(content, filename, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
}
// StreamExcel 流式导出 Excel,dataChan 为数据通道。
func (c *Context) StreamExcel(dataChan <-chan any, filename string, opts ...export.ExcelOption) error {
return c.streamDownload(filename, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", func(w io.Writer) error {
return export.StreamExcel(dataChan, w, opts...)
})
}
// ExportCSV 导出 CSV 文件,filename 为空时使用默认名称。
func (c *Context) ExportCSV(data any, filename string, opts ...export.CSVOption) error {
content, err := export.ExportCSV(data, opts...)
if err != nil {
return err
}
return c.writeDownload(content, filename, "text/csv")
}
// StreamCSV 流式导出 CSV,dataChan 为数据通道。
func (c *Context) StreamCSV(dataChan <-chan any, filename string, opts ...export.CSVOption) error {
return c.streamDownload(filename, "text/csv", func(w io.Writer) error {
return export.StreamCSV(dataChan, w, opts...)
})
}
func (c *Context) writeDownload(content []byte, filename, contentType string) error {
if filename == "" {
switch contentType {
case "text/csv":
filename = "export.csv"
case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
filename = "export.xlsx"
default:
filename = "export"
}
}
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
c.Header("Content-Type", contentType)
c.Header("Content-Length", fmt.Sprintf("%d", len(content)))
c.Status(http.StatusOK)
_, err := c.Writer.Write(content)
return err
}
func (c *Context) streamDownload(filename, contentType string, writeFunc func(io.Writer) error) error {
if filename == "" {
switch contentType {
case "text/csv":
filename = "export.csv"
case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
filename = "export.xlsx"
default:
filename = "export"
}
}
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
c.Header("Content-Type", contentType)
c.Status(http.StatusOK)
return writeFunc(c.Writer)
}