OSDN Git Service

Fix issue #686 RemoveRow slice bounds out of range (#687)
[excelize/excelize.git] / adjust.go
1 // Copyright 2016 - 2020 The excelize Authors. All rights reserved. Use of
2 // this source code is governed by a BSD-style license that can be found in
3 // the LICENSE file.
4 //
5 // Package excelize providing a set of functions that allow you to write to
6 // and read from XLSX / XLSM / XLTM files. Supports reading and writing
7 // spreadsheet documents generated by Microsoft Exce™ 2007 and later. Supports
8 // complex components by high compatibility, and provided streaming API for
9 // generating or reading data from a worksheet with huge amounts of data. This
10 // library needs Go version 1.10 or later.
11
12 package excelize
13
14 import (
15         "errors"
16         "strings"
17 )
18
19 type adjustDirection bool
20
21 const (
22         columns adjustDirection = false
23         rows    adjustDirection = true
24 )
25
26 // adjustHelper provides a function to adjust rows and columns dimensions,
27 // hyperlinks, merged cells and auto filter when inserting or deleting rows or
28 // columns.
29 //
30 // sheet: Worksheet name that we're editing
31 // column: Index number of the column we're inserting/deleting before
32 // row: Index number of the row we're inserting/deleting before
33 // offset: Number of rows/column to insert/delete negative values indicate deletion
34 //
35 // TODO: adjustPageBreaks, adjustComments, adjustDataValidations, adjustProtectedCells
36 //
37 func (f *File) adjustHelper(sheet string, dir adjustDirection, num, offset int) error {
38         xlsx, err := f.workSheetReader(sheet)
39         if err != nil {
40                 return err
41         }
42         if dir == rows {
43                 f.adjustRowDimensions(xlsx, num, offset)
44         } else {
45                 f.adjustColDimensions(xlsx, num, offset)
46         }
47         f.adjustHyperlinks(xlsx, sheet, dir, num, offset)
48         if err = f.adjustMergeCells(xlsx, dir, num, offset); err != nil {
49                 return err
50         }
51         if err = f.adjustAutoFilter(xlsx, dir, num, offset); err != nil {
52                 return err
53         }
54         if err = f.adjustCalcChain(dir, num, offset); err != nil {
55                 return err
56         }
57         checkSheet(xlsx)
58         _ = checkRow(xlsx)
59
60         if xlsx.MergeCells != nil && len(xlsx.MergeCells.Cells) == 0 {
61                 xlsx.MergeCells = nil
62         }
63
64         return nil
65 }
66
67 // adjustColDimensions provides a function to update column dimensions when
68 // inserting or deleting rows or columns.
69 func (f *File) adjustColDimensions(xlsx *xlsxWorksheet, col, offset int) {
70         for rowIdx := range xlsx.SheetData.Row {
71                 for colIdx, v := range xlsx.SheetData.Row[rowIdx].C {
72                         cellCol, cellRow, _ := CellNameToCoordinates(v.R)
73                         if col <= cellCol {
74                                 if newCol := cellCol + offset; newCol > 0 {
75                                         xlsx.SheetData.Row[rowIdx].C[colIdx].R, _ = CoordinatesToCellName(newCol, cellRow)
76                                 }
77                         }
78                 }
79         }
80 }
81
82 // adjustRowDimensions provides a function to update row dimensions when
83 // inserting or deleting rows or columns.
84 func (f *File) adjustRowDimensions(xlsx *xlsxWorksheet, row, offset int) {
85         for i := range xlsx.SheetData.Row {
86                 r := &xlsx.SheetData.Row[i]
87                 if newRow := r.R + offset; r.R >= row && newRow > 0 {
88                         f.ajustSingleRowDimensions(r, newRow)
89                 }
90         }
91 }
92
93 // ajustSingleRowDimensions provides a function to ajust single row dimensions.
94 func (f *File) ajustSingleRowDimensions(r *xlsxRow, num int) {
95         r.R = num
96         for i, col := range r.C {
97                 colName, _, _ := SplitCellName(col.R)
98                 r.C[i].R, _ = JoinCellName(colName, num)
99         }
100 }
101
102 // adjustHyperlinks provides a function to update hyperlinks when inserting or
103 // deleting rows or columns.
104 func (f *File) adjustHyperlinks(xlsx *xlsxWorksheet, sheet string, dir adjustDirection, num, offset int) {
105         // short path
106         if xlsx.Hyperlinks == nil || len(xlsx.Hyperlinks.Hyperlink) == 0 {
107                 return
108         }
109
110         // order is important
111         if offset < 0 {
112                 for i := len(xlsx.Hyperlinks.Hyperlink) - 1; i >= 0; i-- {
113                         linkData := xlsx.Hyperlinks.Hyperlink[i]
114                         colNum, rowNum, _ := CellNameToCoordinates(linkData.Ref)
115
116                         if (dir == rows && num == rowNum) || (dir == columns && num == colNum) {
117                                 f.deleteSheetRelationships(sheet, linkData.RID)
118                                 if len(xlsx.Hyperlinks.Hyperlink) > 1 {
119                                         xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink[:i],
120                                                 xlsx.Hyperlinks.Hyperlink[i+1:]...)
121                                 } else {
122                                         xlsx.Hyperlinks = nil
123                                 }
124                         }
125                 }
126         }
127
128         if xlsx.Hyperlinks == nil {
129                 return
130         }
131
132         for i := range xlsx.Hyperlinks.Hyperlink {
133                 link := &xlsx.Hyperlinks.Hyperlink[i] // get reference
134                 colNum, rowNum, _ := CellNameToCoordinates(link.Ref)
135
136                 if dir == rows {
137                         if rowNum >= num {
138                                 link.Ref, _ = CoordinatesToCellName(colNum, rowNum+offset)
139                         }
140                 } else {
141                         if colNum >= num {
142                                 link.Ref, _ = CoordinatesToCellName(colNum+offset, rowNum)
143                         }
144                 }
145         }
146 }
147
148 // adjustAutoFilter provides a function to update the auto filter when
149 // inserting or deleting rows or columns.
150 func (f *File) adjustAutoFilter(xlsx *xlsxWorksheet, dir adjustDirection, num, offset int) error {
151         if xlsx.AutoFilter == nil {
152                 return nil
153         }
154
155         coordinates, err := f.areaRefToCoordinates(xlsx.AutoFilter.Ref)
156         if err != nil {
157                 return err
158         }
159         x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
160
161         if (dir == rows && y1 == num && offset < 0) || (dir == columns && x1 == num && x2 == num) {
162                 xlsx.AutoFilter = nil
163                 for rowIdx := range xlsx.SheetData.Row {
164                         rowData := &xlsx.SheetData.Row[rowIdx]
165                         if rowData.R > y1 && rowData.R <= y2 {
166                                 rowData.Hidden = false
167                         }
168                 }
169                 return nil
170         }
171
172         coordinates = f.adjustAutoFilterHelper(dir, coordinates, num, offset)
173         x1, y1, x2, y2 = coordinates[0], coordinates[1], coordinates[2], coordinates[3]
174
175         if xlsx.AutoFilter.Ref, err = f.coordinatesToAreaRef([]int{x1, y1, x2, y2}); err != nil {
176                 return err
177         }
178         return nil
179 }
180
181 // adjustAutoFilterHelper provides a function for adjusting auto filter to
182 // compare and calculate cell axis by the given adjust direction, operation
183 // axis and offset.
184 func (f *File) adjustAutoFilterHelper(dir adjustDirection, coordinates []int, num, offset int) []int {
185         if dir == rows {
186                 if coordinates[1] >= num {
187                         coordinates[1] += offset
188                 }
189                 if coordinates[3] >= num {
190                         coordinates[3] += offset
191                 }
192         } else {
193                 if coordinates[2] >= num {
194                         coordinates[2] += offset
195                 }
196         }
197         return coordinates
198 }
199
200 // areaRefToCoordinates provides a function to convert area reference to a
201 // pair of coordinates.
202 func (f *File) areaRefToCoordinates(ref string) ([]int, error) {
203         rng := strings.Split(ref, ":")
204         return areaRangeToCoordinates(rng[0], rng[1])
205 }
206
207 // areaRangeToCoordinates provides a function to convert cell range to a
208 // pair of coordinates.
209 func areaRangeToCoordinates(firstCell, lastCell string) ([]int, error) {
210         coordinates := make([]int, 4)
211         var err error
212         coordinates[0], coordinates[1], err = CellNameToCoordinates(firstCell)
213         if err != nil {
214                 return coordinates, err
215         }
216         coordinates[2], coordinates[3], err = CellNameToCoordinates(lastCell)
217         return coordinates, err
218 }
219
220 // sortCoordinates provides a function to correct the coordinate area, such
221 // correct C1:B3 to B1:C3.
222 func sortCoordinates(coordinates []int) error {
223         if len(coordinates) != 4 {
224                 return errors.New("coordinates length must be 4")
225         }
226         if coordinates[2] < coordinates[0] {
227                 coordinates[2], coordinates[0] = coordinates[0], coordinates[2]
228         }
229         if coordinates[3] < coordinates[1] {
230                 coordinates[3], coordinates[1] = coordinates[1], coordinates[3]
231         }
232         return nil
233 }
234
235 // coordinatesToAreaRef provides a function to convert a pair of coordinates
236 // to area reference.
237 func (f *File) coordinatesToAreaRef(coordinates []int) (string, error) {
238         if len(coordinates) != 4 {
239                 return "", errors.New("coordinates length must be 4")
240         }
241         firstCell, err := CoordinatesToCellName(coordinates[0], coordinates[1])
242         if err != nil {
243                 return "", err
244         }
245         lastCell, err := CoordinatesToCellName(coordinates[2], coordinates[3])
246         if err != nil {
247                 return "", err
248         }
249         return firstCell + ":" + lastCell, err
250 }
251
252 // adjustMergeCells provides a function to update merged cells when inserting
253 // or deleting rows or columns.
254 func (f *File) adjustMergeCells(xlsx *xlsxWorksheet, dir adjustDirection, num, offset int) error {
255         if xlsx.MergeCells == nil {
256                 return nil
257         }
258
259         for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
260                 areaData := xlsx.MergeCells.Cells[i]
261                 coordinates, err := f.areaRefToCoordinates(areaData.Ref)
262                 if err != nil {
263                         return err
264                 }
265                 x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
266                 if dir == rows {
267                         if y1 == num && y2 == num && offset < 0 {
268                                 f.deleteMergeCell(xlsx, i)
269                                 i--
270                         }
271                         y1 = f.adjustMergeCellsHelper(y1, num, offset)
272                         y2 = f.adjustMergeCellsHelper(y2, num, offset)
273                 } else {
274                         if x1 == num && x2 == num && offset < 0 {
275                                 f.deleteMergeCell(xlsx, i)
276                                 i--
277                         }
278                         x1 = f.adjustMergeCellsHelper(x1, num, offset)
279                         x2 = f.adjustMergeCellsHelper(x2, num, offset)
280                 }
281                 if x1 == x2 && y1 == y2 {
282                         f.deleteMergeCell(xlsx, i)
283                         i--
284                 }
285                 if areaData.Ref, err = f.coordinatesToAreaRef([]int{x1, y1, x2, y2}); err != nil {
286                         return err
287                 }
288         }
289         return nil
290 }
291
292 // adjustMergeCellsHelper provides a function for adjusting merge cells to
293 // compare and calculate cell axis by the given pivot, operation axis and
294 // offset.
295 func (f *File) adjustMergeCellsHelper(pivot, num, offset int) int {
296         if pivot >= num {
297                 pivot += offset
298                 if pivot < 1 {
299                         return 1
300                 }
301                 return pivot
302         }
303         return pivot
304 }
305
306 // deleteMergeCell provides a function to delete merged cell by given index.
307 func (f *File) deleteMergeCell(sheet *xlsxWorksheet, idx int) {
308         if len(sheet.MergeCells.Cells) > idx {
309                 sheet.MergeCells.Cells = append(sheet.MergeCells.Cells[:idx], sheet.MergeCells.Cells[idx+1:]...)
310                 sheet.MergeCells.Count = len(sheet.MergeCells.Cells)
311         }
312 }
313
314 // adjustCalcChain provides a function to update the calculation chain when
315 // inserting or deleting rows or columns.
316 func (f *File) adjustCalcChain(dir adjustDirection, num, offset int) error {
317         if f.CalcChain == nil {
318                 return nil
319         }
320         for index, c := range f.CalcChain.C {
321                 colNum, rowNum, err := CellNameToCoordinates(c.R)
322                 if err != nil {
323                         return err
324                 }
325                 if dir == rows && num <= rowNum {
326                         if newRow := rowNum + offset; newRow > 0 {
327                                 f.CalcChain.C[index].R, _ = CoordinatesToCellName(colNum, newRow)
328                         }
329                 }
330                 if dir == columns && num <= colNum {
331                         if newCol := colNum + offset; newCol > 0 {
332                                 f.CalcChain.C[index].R, _ = CoordinatesToCellName(newCol, rowNum)
333                         }
334                 }
335         }
336         return nil
337 }