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 "errors"
5 "math"
6 "strconv"
7
8 "github.com/xuri/excelize/v2"
9
10 "amadan.net/oficina/sheets/internal/sheets/store"
11)
12
13// importer carries one import's state across its cells.
14type importer struct {
15 f *excelize.File
16 sheet string
17 h *store.Handle
18 scan *sheetScan
19 base *excelize.Style
20 rep *Report
21 kept []keptFormula
22 // capped is set when any write's recalculation was too wide to
23 // run (calc.MaxDirtyPerPass): its dependents stay dirty until the
24 // tab is next opened, so no value read during this import can be
25 // trusted as final.
26 capped bool
27}
28
29// keptFormula is a formula written as a formula, remembered so its
30// result can be compared with its saved value once every cell it could
31// depend on has been written.
32type keptFormula struct {
33 pos posKey
34 rowID, colID uint64
35 saved scannedCell
36 volatile bool
37}
38
39// Refusals a cell can cause. Each becomes a CellError, so the
40// coordinate is data and the cause stays out of the error's text.
41var (
42 errTextTooLong = errors.New("xlsx: text needs a wrapper past the input limit")
43 errCellIsError = errors.New("xlsx: cell holds an error value")
44 errCellNotNumber = errors.New("xlsx: number cell is not a finite number")
45 errCellType = errors.New("xlsx: cell type is not one import reads")
46)
47
48// cell imports one position. It creates the backing Row/Col only if
49// the cell has content or a format worth recording — an interior blank
50// cell with neither leaves no trace, matching the sparse model
51// (models.go's comment on Cell).
52func (im *importer) cell(p posKey, raw string) error {
53 ref, err := excelize.CoordinatesToCellName(p.Col+1, p.Row+1)
54 if err != nil {
55 return cellErr("cannot address cell", p.Row, p.Col, err)
56 }
57 formula, err := im.f.GetCellFormula(im.sheet, ref)
58 if err != nil {
59 return cellErr("cannot read the formula at", p.Row, p.Col, err)
60 }
61 sc, scanned := im.scan.Cells[p]
62 if (formula != "") != (scanned && sc.HasF) {
63 return cellErr("the workbook's parts disagree at", p.Row, p.Col, errScanInconsistent)
64 }
65 if scanned {
66 if err := im.agree(ref, sc); err != nil {
67 return cellErr("the workbook's parts disagree at", p.Row, p.Col, err)
68 }
69 }
70
71 var (
72 input string
73 cls formulaClass
74 )
75 if formula != "" {
76 cls = classify(formula, sc.FType)
77 input, err = im.formulaInput(p, formula, cls, sc)
78 } else {
79 input, err = im.literalInput(p, ref, raw, sc, scanned)
80 }
81 if err != nil {
82 return err
83 }
84
85 styleID, err := im.f.GetCellStyle(im.sheet, ref)
86 if err != nil {
87 return cellErr("cannot read the style at", p.Row, p.Col, err)
88 }
89 style, err := im.f.GetStyle(styleID)
90 if err != nil {
91 return cellErr("cannot read the style at", p.Row, p.Col, err)
92 }
93 format, hasFormat := formatFromStyle(style)
94 if input == "" && !hasFormat {
95 return nil // nothing here worth a Row/Col at all
96 }
97 if partialStyle(style, im.base) {
98 im.rep.cell(FormatPartial, p.Row, p.Col)
99 }
100
101 rowID, err := im.h.EnsureRow(p.Row)
102 if err != nil {
103 return cellErr("cannot make the row for cell", p.Row, p.Col, err)
104 }
105 colID, err := im.h.EnsureCol(p.Col)
106 if err != nil {
107 return cellErr("cannot make the column for cell", p.Row, p.Col, err)
108 }
109 if input != "" {
110 rep, err := im.h.SetReport(rowID, colID, input, importActor)
111 if err != nil {
112 return cellErr("cannot parse cell", p.Row, p.Col, err)
113 }
114 im.capped = im.capped || rep.Capped
115 }
116 if hasFormat {
117 if err := im.h.SetFormat(rowID, colID, format); err != nil {
118 return cellErr("cannot set the format at", p.Row, p.Col, err)
119 }
120 }
121 if formula != "" && cls.Supported {
122 im.kept = append(im.kept, keptFormula{pos: p, rowID: rowID, colID: colID,
123 saved: sc, volatile: cls.Volatile})
124 }
125 return nil
126}
127
128// formulaInput is a formula cell's raw input: the formula itself when
129// it is supported, otherwise its saved value, reported.
130func (im *importer) formulaInput(p posKey, formula string, cls formulaClass, sc scannedCell) (string, error) {
131 if cls.Supported {
132 return "=" + formula, nil
133 }
134 v, err := savedValue(sc)
135 if err != nil {
136 return "", cellErr("a formula has no usable saved value at", p.Row, p.Col, err)
137 }
138 input, wrapped := frozenInput(v)
139 if wrapped && len(input) > store.MaxInputBytes {
140 return "", cellErr("text is too long to keep as text at", p.Row, p.Col, errTextTooLong)
141 }
142 im.rep.cell(cls.Code, p.Row, p.Col)
143 if wrapped {
144 im.rep.cell(TextKept, p.Row, p.Col)
145 }
146 return input, nil
147}
148
149// literalInput is a non-formula cell's raw input, typed by what the
150// workbook declared the cell to be rather than by what its text looks
151// like.
152func (im *importer) literalInput(p posKey, ref, raw string, sc scannedCell, scanned bool) (string, error) {
153 cellType, err := im.f.GetCellType(im.sheet, ref)
154 if err != nil {
155 return "", cellErr("cannot read the cell type at", p.Row, p.Col, err)
156 }
157 switch cellType {
158 case excelize.CellTypeSharedString, excelize.CellTypeInlineString, excelize.CellTypeFormula:
159 // Text. An empty string is text too, where the workbook wrote
160 // one: an inline string, or a <v> the scan saw.
161 if raw == "" && !(scanned && (sc.HasV || sc.T == "inlineStr")) {
162 return "", nil
163 }
164 input, wrapped := store.TextInput(raw)
165 if wrapped {
166 if len(input) > store.MaxInputBytes {
167 return "", cellErr("text is too long to keep as text at", p.Row, p.Col, errTextTooLong)
168 }
169 im.rep.cell(TextKept, p.Row, p.Col)
170 }
171 return input, nil
172 case excelize.CellTypeBool:
173 switch raw {
174 case "1":
175 return "TRUE", nil
176 case "0":
177 return "FALSE", nil
178 }
179 return "", cellErr("cannot read the boolean at", p.Row, p.Col, errCellType)
180 case excelize.CellTypeUnset, excelize.CellTypeNumber:
181 if raw == "" {
182 return "", nil
183 }
184 n, err := strconv.ParseFloat(raw, 64)
185 if err != nil || math.IsNaN(n) || math.IsInf(n, 0) {
186 return "", cellErr("cannot read the number at", p.Row, p.Col, errCellNotNumber)
187 }
188 return raw, nil
189 case excelize.CellTypeError:
190 return "", cellErr("a cell holds an error value at", p.Row, p.Col, errCellIsError)
191 }
192 return "", cellErr("cannot read the cell type at", p.Row, p.Col, errCellType)
193}
194
195// compare checks every kept formula against the value its workbook
196// saved, after the last cell is written so each result is final.
197//
198// Final only if no write was capped. A capped write leaves dependents
199// dirty until the tab is next opened, and a stale value could match or
200// miss a saved one by accident, so then nothing is compared: every
201// kept formula is reported unchecked instead.
202func (im *importer) compare() {
203 for _, k := range im.kept {
204 saved, ok := comparableSaved(k.saved)
205 if !ok || k.volatile || im.capped {
206 im.rep.cell(FormulaUnchecked, k.pos.Row, k.pos.Col)
207 continue
208 }
209 if !sameValue(im.h.Value(k.rowID, k.colID), saved) {
210 im.rep.cell(FormulaDiffers, k.pos.Row, k.pos.Col)
211 }
212 }
213}
214
215// scanTypes maps a c element's t to excelize's reading of it, absent
216// and unknown both reading as Unset, as excelize's own table does.
217var scanTypes = map[string]excelize.CellType{
218 "b": excelize.CellTypeBool, "d": excelize.CellTypeDate, "n": excelize.CellTypeNumber,
219 "e": excelize.CellTypeError, "s": excelize.CellTypeSharedString,
220 "str": excelize.CellTypeFormula, "inlineStr": excelize.CellTypeInlineString,
221}
222
223// agree checks that excelize read a scanned cell as the scan did: the
224// same declared type and, for a formula whose <v> is the value itself
225// rather than an index or a date, the same saved value. Either reader
226// could be the one that is wrong; a disagreement stops the import
227// rather than let one of them quietly supply the value.
228func (im *importer) agree(ref string, sc scannedCell) error {
229 cellType, err := im.f.GetCellType(im.sheet, ref)
230 if err != nil {
231 return err
232 }
233 if cellType != scanTypes[sc.T] {
234 return errScanInconsistent
235 }
236 if !sc.HasF || sc.T == "s" || sc.T == "inlineStr" || sc.T == "d" {
237 return nil
238 }
239 raw, err := im.f.GetCellValue(im.sheet, ref, excelize.Options{RawCellValue: true})
240 if err != nil {
241 return err
242 }
243 if raw != sc.V {
244 return errScanInconsistent
245 }
246 return nil
247}
248