forked from ivahaev/go-xlsx-templater
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxlst.go
377 lines (316 loc) · 7.47 KB
/
xlst.go
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package xlst
import (
"errors"
"fmt"
"io"
"reflect"
"regexp"
"strings"
"github.com/aymerick/raymond"
"github.com/kkbblzq/xlsx/v3"
)
var (
rgx = regexp.MustCompile(`\{\{\s*(\w+)\.\w+\s*\}\}`)
rangeRgx = regexp.MustCompile(`\{\{\s*range\s+(\w+)\s*\}\}`)
rangeEndRgx = regexp.MustCompile(`\{\{\s*end\s*\}\}`)
)
// Xlst Represents template struct
type Xlst struct {
file *xlsx.File
report *xlsx.File
}
// Options for render has only one property WrapTextInAllCells for wrapping text
type Options struct {
WrapTextInAllCells bool
}
// New creates new Xlst struct and returns pointer to it
func New() *Xlst {
return &Xlst{}
}
// NewFromBinary creates new Xlst struct puts binary tempate into and returns pointer to it
func NewFromBinary(content []byte) (*Xlst, error) {
file, err := xlsx.OpenBinary(content)
if err != nil {
return nil, err
}
res := &Xlst{file: file}
return res, nil
}
// Render renders report and stores it in a struct
func (m *Xlst) Render(in interface{}) error {
return m.RenderWithOptions(in, nil)
}
func (m *Xlst) getRows(st *xlsx.Sheet) ([]*xlsx.Row, error) {
rows := make([]*xlsx.Row, 0, st.MaxRow)
if err := st.ForEachRow(func(r *xlsx.Row) error {
rows = append(rows, r)
return nil
}); err != nil {
return nil, err
}
return rows, nil
}
// RenderWithOptions renders report with options provided and stores it in a struct
func (m *Xlst) RenderWithOptions(in interface{}, options *Options) error {
if options == nil {
options = new(Options)
}
report := xlsx.NewFile()
for si, sheet := range m.file.Sheets {
ctx := getCtx(in, si)
newSheet, err := report.AddSheet(sheet.Name)
if err != nil {
return err
}
cloneSheet(sheet, newSheet)
rows, err := m.getRows(sheet)
if err != nil {
return err
}
if err = renderRows(newSheet, rows, ctx, options); err != nil {
return err
}
sheet.Cols.ForEach(func(idx int, col *xlsx.Col) {
newSheet.Cols.Add(col)
})
}
m.report = report
return nil
}
// ReadTemplate reads template from disk and stores it in a struct
func (m *Xlst) ReadTemplate(path string) error {
file, err := xlsx.OpenFile(path)
if err != nil {
return err
}
m.file = file
return nil
}
// Save saves generated report to disk
func (m *Xlst) Save(path string) error {
if m.report == nil {
return errors.New("Report was not generated")
}
return m.report.Save(path)
}
// Write writes generated report to provided writer
func (m *Xlst) Write(writer io.Writer) error {
if m.report == nil {
return errors.New("Report was not generated")
}
return m.report.Write(writer)
}
func renderRows(sheet *xlsx.Sheet, rows []*xlsx.Row, ctx map[string]interface{}, options *Options) error {
for ri := 0; ri < len(rows); ri++ {
row := rows[ri]
rangeProp := getRangeProp(row)
if rangeProp != "" {
ri++
rangeEndIndex := getRangeEndIndex(rows[ri:])
if rangeEndIndex == -1 {
return fmt.Errorf("End of range %q not found", rangeProp)
}
rangeEndIndex += ri
rangeCtx := getRangeCtx(ctx, rangeProp)
if rangeCtx == nil {
return fmt.Errorf("Not expected context property for range %q", rangeProp)
}
for idx := range rangeCtx {
localCtx := mergeCtx(rangeCtx[idx], ctx)
err := renderRows(sheet, rows[ri:rangeEndIndex], localCtx, options)
if err != nil {
return err
}
}
ri = rangeEndIndex
continue
}
prop := getListProp(row)
if prop == "" {
newRow := sheet.AddRow()
if err := cloneRow(row, newRow, options); err != nil {
return err
}
if err := renderRow(newRow, ctx); err != nil {
return err
}
continue
}
if !isArray(ctx, prop) {
newRow := sheet.AddRow()
if err := cloneRow(row, newRow, options); err != nil {
return err
}
err := renderRow(newRow, ctx)
if err != nil {
return err
}
continue
}
arr := reflect.ValueOf(ctx[prop])
arrBackup := ctx[prop]
for i := 0; i < arr.Len(); i++ {
newRow := sheet.AddRow()
if err := cloneRow(row, newRow, options); err != nil {
return err
}
ctx[prop] = arr.Index(i).Interface()
err := renderRow(newRow, ctx)
if err != nil {
return err
}
}
ctx[prop] = arrBackup
}
return nil
}
func cloneCell(from, to *xlsx.Cell, options *Options) error {
fromBin, err := from.MarshalBinary()
if err != nil {
return err
}
if err := to.UnmarshalBinary(fromBin); err != nil {
return err
}
style := from.GetStyle()
if options.WrapTextInAllCells {
style.Alignment.WrapText = true
}
to.SetStyle(style)
if from.Value == "" && len(from.RichText) > 0 {
to.SetRichText(from.RichText)
}
return nil
}
func cloneRow(from, to *xlsx.Row, options *Options) error {
if from.GetHeight() != 0 {
to.SetHeight(from.GetHeight())
}
return from.ForEachCell(func(cell *xlsx.Cell) error {
newCell := to.AddCell()
return cloneCell(cell, newCell, options)
})
}
func renderCell(cell *xlsx.Cell, ctx interface{}) error {
tpl := strings.Replace(cell.Value, "{{", "{{{", -1)
tpl = strings.Replace(tpl, "}}", "}}}", -1)
template, err := raymond.Parse(tpl)
if err != nil {
return err
}
out, err := template.Exec(ctx)
if err != nil {
return err
}
cell.Value = out
return nil
}
func cloneSheet(from, to *xlsx.Sheet) {
from.Cols.ForEach(func(idx int, col *xlsx.Col) {
newCol := xlsx.NewColForRange(col.Min, col.Max)
style := col.GetStyle()
newCol.SetStyle(style)
newCol.Width = col.Width
newCol.Hidden = col.Hidden
newCol.Collapsed = col.Collapsed
newCol.CustomWidth = col.CustomWidth
newCol.OutlineLevel = col.OutlineLevel
newCol.Phonetic = col.Phonetic
to.Cols.Add(col)
})
}
func getCtx(in interface{}, i int) map[string]interface{} {
if ctx, ok := in.(map[string]interface{}); ok {
return ctx
}
if ctxSlice, ok := in.([]interface{}); ok {
if len(ctxSlice) > i {
_ctx := ctxSlice[i]
if ctx, ok := _ctx.(map[string]interface{}); ok {
return ctx
}
}
return nil
}
return nil
}
func getRangeCtx(ctx map[string]interface{}, prop string) []map[string]interface{} {
val, ok := ctx[prop]
if !ok {
return nil
}
if propCtx, ok := val.([]map[string]interface{}); ok {
return propCtx
}
return nil
}
func mergeCtx(local, global map[string]interface{}) map[string]interface{} {
ctx := make(map[string]interface{})
for k, v := range global {
ctx[k] = v
}
for k, v := range local {
ctx[k] = v
}
return ctx
}
func isArray(in map[string]interface{}, prop string) bool {
val, ok := in[prop]
if !ok {
return false
}
switch reflect.TypeOf(val).Kind() {
case reflect.Array, reflect.Slice:
return true
}
return false
}
func getListProp(in *xlsx.Row) string {
for i := 0; i < in.Sheet.MaxCol; i++ {
cell := in.GetCell(i)
if cell.Value == "" {
continue
}
if match := rgx.FindAllStringSubmatch(cell.Value, -1); match != nil {
return match[0][1]
}
}
return ""
}
func getRangeProp(in *xlsx.Row) string {
if in.Sheet.MaxCol != 0 {
match := rangeRgx.FindAllStringSubmatch(in.GetCell(0).Value, -1)
if match != nil {
return match[0][1]
}
}
return ""
}
func getRangeEndIndex(rows []*xlsx.Row) int {
var nesting int
for idx := 0; idx < len(rows); idx++ {
if rows[idx].Sheet.MaxCol == 0 {
continue
}
if rangeEndRgx.MatchString(rows[idx].GetCell(0).Value) {
if nesting == 0 {
return idx
}
nesting--
continue
}
if rangeRgx.MatchString(rows[idx].GetCell(0).Value) {
nesting++
}
}
return -1
}
func renderRow(in *xlsx.Row, ctx interface{}) error {
return in.ForEachCell(func(cell *xlsx.Cell) error {
err := renderCell(cell, ctx)
if err != nil {
return err
}
return nil
})
}