-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefinedname.go
More file actions
86 lines (73 loc) · 2.41 KB
/
Copy pathdefinedname.go
File metadata and controls
86 lines (73 loc) · 2.41 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
79
80
81
82
83
84
85
86
package xlfill
import (
"fmt"
"github.com/xuri/excelize/v2"
)
// DefinedNameCommand implements the jx:definedName command.
// It processes its inner area normally, then registers a deferred action
// that creates an Excel defined name (named range) for the expanded output range.
type DefinedNameCommand struct {
DefinedNameValue string // the defined name
Scope string // scope: "workbook" (default) or a sheet name
Area *Area
}
func (c *DefinedNameCommand) Name() string { return "definedName" }
func (c *DefinedNameCommand) Reset() {}
func (c *DefinedNameCommand) GetArea() *Area { return c.Area }
func (c *DefinedNameCommand) SetArea(a *Area) { c.Area = a }
// newDefinedNameCommandFromAttrs creates a DefinedNameCommand from parsed attributes.
func newDefinedNameCommandFromAttrs(attrs map[string]string) (Command, error) {
cmd := &DefinedNameCommand{
DefinedNameValue: attrs["name"],
Scope: attrs["scope"],
}
if cmd.DefinedNameValue == "" {
return nil, fmt.Errorf("definedName command requires 'name' attribute")
}
if cmd.Scope == "" {
cmd.Scope = "workbook"
}
return cmd, nil
}
// ApplyAt processes the inner area, then registers a deferred action for the defined name.
func (c *DefinedNameCommand) ApplyAt(cellRef CellRef, ctx *Context, transformer Transformer) (Size, error) {
if c.Area == nil {
return ZeroSize, nil
}
// Process the inner area normally first
size, err := c.Area.ApplyAt(cellRef, ctx)
if err != nil {
return ZeroSize, err
}
// Capture values for the closure
sheet := cellRef.Sheet
startRow := cellRef.Row
startCol := cellRef.Col
endRow := cellRef.Row + size.Height - 1
endCol := cellRef.Col + size.Width - 1
definedName := c.DefinedNameValue
scope := c.Scope
// Register deferred action
if err := ctx.RegisterDeferred(DeferredAction{
Name: "definedName",
Sheet: sheet,
StartRow: startRow,
StartCol: startCol,
EndRow: endRow,
EndCol: endCol,
Execute: func(tx *ExcelizeTransformer) error {
startColName := ColToName(startCol)
endColName := ColToName(endCol)
refersTo := fmt.Sprintf("'%s'!$%s$%d:$%s$%d", sheet, startColName, startRow+1, endColName, endRow+1)
dn := &excelize.DefinedName{
Name: definedName,
RefersTo: refersTo,
Scope: scope,
}
return tx.file.SetDefinedName(dn)
},
}); err != nil {
return ZeroSize, fmt.Errorf("definedName: %w", err)
}
return size, nil
}