oficina / sheets Public

Clone
git clone https://amadan.net/oficina/sheets

Plain git — no account needed to clone.

Download

Download this file

1package xlsx
2
3import (
4 "encoding/xml"
5 "errors"
6 "io"
7 "strconv"
8
9 "github.com/xuri/excelize/v2"
10
11 "amadan.net/oficina/sheets/internal/sheets/store"
12)
13
14// scannedCell is one <c> as the worksheet XML wrote it.
15//
16// It exists for what excelize cannot say. excelize's cell model keeps
17// <v> as a plain string with omitempty, so a formula whose saved value
18// is the empty string and a formula with no saved value at all read
19// the same; this reader records whether <v> was there.
20type scannedCell struct {
21 T string // the c element's t attribute: "", "n", "b", "e", "s", "str", "inlineStr", "d"
22 HasF bool
23 FType string // the f element's t attribute: "", "normal", "shared", "array", "dataTable"
24 HasV bool
25 V string
26}
27
28// sheetScan is what a bounded read of the first worksheet found.
29type sheetScan struct {
30 // Name is the first sheet's name, compared with excelize's.
31 Name string
32 // Cells holds every formula cell and every string-typed cell.
33 Cells map[posKey]scannedCell
34 // Layout and features the import does not carry, counted.
35 Hyperlinks, HiddenRows, HiddenCols int
36 FrozenPane, AutoFilter bool
37 // Charts and Images are workbook-wide part counts.
38 Charts, Images int
39}
40
41type posKey struct{ Row, Col int }
42
43// errCellWithoutRef is a formula or string cell whose position the XML
44// leaves implicit. excelize would place it by order; this reader does
45// not guess, so the two could disagree about where it is.
46var errCellWithoutRef = errors.New("xlsx: a cell has no reference")
47
48// scanWorkbook reads the first worksheet's XML directly, bounded.
49func scanWorkbook(data []byte) (*sheetScan, error) {
50 parts, err := openParts(data)
51 if err != nil {
52 return nil, err
53 }
54 sheetPath, name, err := firstWorksheetPath(parts)
55 if err != nil {
56 return nil, err
57 }
58 rc, err := parts.open(sheetPath, maxSheetBytes)
59 if err != nil {
60 return nil, err
61 }
62 defer rc.Close()
63
64 s := &sheetScan{
65 Name: name,
66 Cells: map[posKey]scannedCell{},
67 Charts: parts.count("xl/charts/chart"),
68 Images: parts.count("xl/media/"),
69 }
70 if err := s.walk(xml.NewDecoder(rc)); err != nil {
71 return nil, err
72 }
73 return s, nil
74}
75
76// Paths the walk acts on, as the stack of local names above an
77// element. Matching the whole path, not just the parent, is what keeps
78// a <c> or a <v> inside some extension element from being read as a
79// cell: excelize unmarshals by the same paths, so anything elsewhere is
80// invisible to it, and must be to this reader too.
81var (
82 pathRow = []string{"worksheet", "sheetData"}
83 pathCell = []string{"worksheet", "sheetData", "row"}
84 pathCellChild = []string{"worksheet", "sheetData", "row", "c"}
85 pathCol = []string{"worksheet", "cols"}
86 pathHyperlink = []string{"worksheet", "hyperlinks"}
87 pathPane = []string{"worksheet", "sheetViews", "sheetView"}
88 pathSheet = []string{"worksheet"}
89)
90
91// formulaTypes are the <f t> values ECMA-376 defines. Any other is a
92// formula whose meaning this reader does not know, and is refused.
93var formulaTypes = map[string]bool{"": true, "normal": true, "shared": true, "array": true, "dataTable": true}
94
95// errScanDuplicate is a cell written twice, or a cell with two <f> or
96// two <v>. Which one wins is a parser's accident; import refuses to
97// depend on it.
98var errScanDuplicate = errors.New("xlsx: worksheet repeats a cell or its parts")
99
100// maxScannedCells bounds the set of every <c> reference the walk has
101// seen, which duplicate detection needs.
102const maxScannedCells = 2 * store.MaxCellsPerTab
103
104// walk streams the worksheet, bounded in depth by the stack.
105func (s *sheetScan) walk(d *xml.Decoder) error {
106 var (
107 stack []string
108 cell scannedCell
109 ref string
110 rowNum string
111 fs, vs int
112 seen = map[posKey]bool{}
113 )
114 for {
115 tok, err := d.Token()
116 if err == io.EOF {
117 return nil
118 }
119 if err != nil {
120 return err
121 }
122 switch t := tok.(type) {
123 case xml.StartElement:
124 if len(stack) >= maxXMLDepth {
125 return errScanLimit
126 }
127 name := t.Name.Local
128 switch {
129 case name == "row" && at(stack, pathRow):
130 rowNum = attr(t, "r")
131 if truthy(attr(t, "hidden")) {
132 s.HiddenRows++
133 }
134 case name == "c" && at(stack, pathCell):
135 cell, ref, fs, vs = scannedCell{T: attr(t, "t")}, attr(t, "r"), 0, 0
136 if ref != "" {
137 col, row, err := excelize.CellNameToCoordinates(ref)
138 if err != nil {
139 return errScanInconsistent
140 }
141 p := posKey{Row: row - 1, Col: col - 1}
142 if seen[p] {
143 return errScanDuplicate
144 }
145 if len(seen) >= maxScannedCells {
146 return store.ErrTabTooLarge
147 }
148 seen[p] = true
149 }
150 case name == "f" && at(stack, pathCellChild):
151 fs++
152 cell.HasF, cell.FType = true, attr(t, "t")
153 if !formulaTypes[cell.FType] {
154 return errScanInconsistent
155 }
156 case name == "v" && at(stack, pathCellChild):
157 vs++
158 cell.HasV = true
159 case name == "col" && at(stack, pathCol):
160 if truthy(attr(t, "hidden")) {
161 s.HiddenCols++
162 }
163 case name == "hyperlink" && at(stack, pathHyperlink):
164 s.Hyperlinks++
165 case name == "pane" && at(stack, pathPane):
166 st := attr(t, "state")
167 s.FrozenPane = s.FrozenPane || st == "frozen" || st == "frozenSplit"
168 case name == "autoFilter" && at(stack, pathSheet):
169 s.AutoFilter = true
170 }
171 if fs > 1 || vs > 1 {
172 return errScanDuplicate
173 }
174 stack = append(stack, name)
175 case xml.CharData:
176 if len(stack) == len(pathCellChild)+1 && stack[len(stack)-1] == "v" && at(stack[:len(stack)-1], pathCellChild) {
177 if len(cell.V)+len(t) > maxCachedBytes {
178 return errScanLimit
179 }
180 cell.V += string(t)
181 }
182 case xml.EndElement:
183 stack = stack[:len(stack)-1]
184 if t.Name.Local == "c" && at(stack, pathCell) {
185 if err := s.keep(ref, rowNum, cell); err != nil {
186 return err
187 }
188 }
189 }
190 }
191}
192
193// at reports whether stack is exactly path.
194func at(stack, path []string) bool {
195 if len(stack) != len(path) {
196 return false
197 }
198 for i := range path {
199 if stack[i] != path[i] {
200 return false
201 }
202 }
203 return true
204}
205
206// keep records a cell the import needs to know about: one with a
207// formula, or one typed as a string (whose value may be the empty
208// string, which excelize's row reader drops from the end of a row).
209func (s *sheetScan) keep(ref, rowNum string, c scannedCell) error {
210 if !c.HasF && c.T != "s" && c.T != "inlineStr" && c.T != "str" {
211 return nil
212 }
213 if ref == "" {
214 return errCellWithoutRef
215 }
216 col, row, err := excelize.CellNameToCoordinates(ref)
217 if err != nil {
218 return errScanInconsistent
219 }
220 if rowNum != "" && rowNum != strconv.Itoa(row) {
221 return errScanInconsistent // a cell filed under another row
222 }
223 s.Cells[posKey{Row: row - 1, Col: col - 1}] = c
224 return nil
225}
226
227func attr(t xml.StartElement, local string) string {
228 for _, a := range t.Attr {
229 if a.Name.Local == local { // by local name, as excelize's struct tags match
230 return a.Value
231 }
232 }
233 return ""
234}
235
236func truthy(v string) bool { return v == "1" || v == "true" }
237