OSDN Git Service

Fix #724, standardize variable naming and update unit tests
[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         ws, err := f.workSheetReader(sheet)
39         if err != nil {
40                 return err
41         }
42         if dir == rows {
43                 f.adjustRowDimensions(ws, num, offset)
44         } else {
45                 f.adjustColDimensions(ws, num, offset)
46         }
47         f.adjustHyperlinks(ws, sheet, dir, num, offset)
48         if err = f.adjustMergeCells(ws, dir, num, offset); err != nil {
49                 return err
50         }
51         if err = f.adjustAutoFilter(ws, 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(ws)
58         _ = checkRow(ws)
59
60         if ws.MergeCells != nil && len(ws.MergeCells.Cells) == 0 {
61                 ws.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(ws *xlsxWorksheet, col, offset int) {
70         for rowIdx := range ws.SheetData.Row {
71                 for colIdx, v := range ws.SheetData.Row[rowIdx].C {
72                         cellCol, cellRow, _ := CellNameToCoordinates(v.R)
73                         if col <= cellCol {
74                                 if newCol := cellCol + offset; newCol > 0 {
75                                         ws.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(ws *xlsxWorksheet, row, offset int) {
85         for i := range ws.SheetData.Row {
86                 r := &ws.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(ws *xlsxWorksheet, sheet string, dir adjustDirection, num, offset int) {
105         // short path
106         if ws.Hyperlinks == nil || len(ws.Hyperlinks.Hyperlink) == 0 {
107                 return
108         }
109
110         // order is important
111         if offset < 0 {
112                 for i := len(ws.Hyperlinks.Hyperlink) - 1; i >= 0; i-- {
113                         linkData := ws.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(ws.Hyperlinks.Hyperlink) > 1 {
119                                         ws.Hyperlinks.Hyperlink = append(ws.Hyperlinks.Hyperlink[:i],
120                                                 ws.Hyperlinks.Hyperlink[i+1:]...)
121                                 } else {
122                                         ws.Hyperlinks = nil
123                                 }
124                         }
125                 }
126         }
127         if ws.Hyperlinks == nil {
128                 return
129         }
130         for i := range ws.Hyperlinks.Hyperlink {
131                 link := &ws.Hyperlinks.Hyperlink[i] // get reference
132                 colNum, rowNum, _ := CellNameToCoordinates(link.Ref)
133                 if dir == rows {
134                         if rowNum >= num {
135                                 link.Ref, _ = CoordinatesToCellName(colNum, rowNum+offset)
136                         }
137                 } else {
138                         if colNum >= num {
139                                 link.Ref, _ = CoordinatesToCellName(colNum+offset, rowNum)
140                         }
141                 }
142         }
143 }
144
145 // adjustAutoFilter provides a function to update the auto filter when
146 // inserting or deleting rows or columns.
147 func (f *File) adjustAutoFilter(ws *xlsxWorksheet, dir adjustDirection, num, offset int) error {
148         if ws.AutoFilter == nil {
149                 return nil
150         }
151
152         coordinates, err := f.areaRefToCoordinates(ws.AutoFilter.Ref)
153         if err != nil {
154                 return err
155         }
156         x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
157
158         if (dir == rows && y1 == num && offset < 0) || (dir == columns && x1 == num && x2 == num) {
159                 ws.AutoFilter = nil
160                 for rowIdx := range ws.SheetData.Row {
161                         rowData := &ws.SheetData.Row[rowIdx]
162                         if rowData.R > y1 && rowData.R <= y2 {
163                                 rowData.Hidden = false
164                         }
165                 }
166                 return nil
167         }
168
169         coordinates = f.adjustAutoFilterHelper(dir, coordinates, num, offset)
170         x1, y1, x2, y2 = coordinates[0], coordinates[1], coordinates[2], coordinates[3]
171
172         if ws.AutoFilter.Ref, err = f.coordinatesToAreaRef([]int{x1, y1, x2, y2}); err != nil {
173                 return err
174         }
175         return nil
176 }
177
178 // adjustAutoFilterHelper provides a function for adjusting auto filter to
179 // compare and calculate cell axis by the given adjust direction, operation
180 // axis and offset.
181 func (f *File) adjustAutoFilterHelper(dir adjustDirection, coordinates []int, num, offset int) []int {
182         if dir == rows {
183                 if coordinates[1] >= num {
184                         coordinates[1] += offset
185                 }
186                 if coordinates[3] >= num {
187                         coordinates[3] += offset
188                 }
189         } else {
190                 if coordinates[2] >= num {
191                         coordinates[2] += offset
192                 }
193         }
194         return coordinates
195 }
196
197 // areaRefToCoordinates provides a function to convert area reference to a
198 // pair of coordinates.
199 func (f *File) areaRefToCoordinates(ref string) ([]int, error) {
200         rng := strings.Split(ref, ":")
201         return areaRangeToCoordinates(rng[0], rng[1])
202 }
203
204 // areaRangeToCoordinates provides a function to convert cell range to a
205 // pair of coordinates.
206 func areaRangeToCoordinates(firstCell, lastCell string) ([]int, error) {
207         coordinates := make([]int, 4)
208         var err error
209         coordinates[0], coordinates[1], err = CellNameToCoordinates(firstCell)
210         if err != nil {
211                 return coordinates, err
212         }
213         coordinates[2], coordinates[3], err = CellNameToCoordinates(lastCell)
214         return coordinates, err
215 }
216
217 // sortCoordinates provides a function to correct the coordinate area, such
218 // correct C1:B3 to B1:C3.
219 func sortCoordinates(coordinates []int) error {
220         if len(coordinates) != 4 {
221                 return errors.New("coordinates length must be 4")
222         }
223         if coordinates[2] < coordinates[0] {
224                 coordinates[2], coordinates[0] = coordinates[0], coordinates[2]
225         }
226         if coordinates[3] < coordinates[1] {
227                 coordinates[3], coordinates[1] = coordinates[1], coordinates[3]
228         }
229         return nil
230 }
231
232 // coordinatesToAreaRef provides a function to convert a pair of coordinates
233 // to area reference.
234 func (f *File) coordinatesToAreaRef(coordinates []int) (string, error) {
235         if len(coordinates) != 4 {
236                 return "", errors.New("coordinates length must be 4")
237         }
238         firstCell, err := CoordinatesToCellName(coordinates[0], coordinates[1])
239         if err != nil {
240                 return "", err
241         }
242         lastCell, err := CoordinatesToCellName(coordinates[2], coordinates[3])
243         if err != nil {
244                 return "", err
245         }
246         return firstCell + ":" + lastCell, err
247 }
248
249 // adjustMergeCells provides a function to update merged cells when inserting
250 // or deleting rows or columns.
251 func (f *File) adjustMergeCells(ws *xlsxWorksheet, dir adjustDirection, num, offset int) error {
252         if ws.MergeCells == nil {
253                 return nil
254         }
255
256         for i := 0; i < len(ws.MergeCells.Cells); i++ {
257                 areaData := ws.MergeCells.Cells[i]
258                 coordinates, err := f.areaRefToCoordinates(areaData.Ref)
259                 if err != nil {
260                         return err
261                 }
262                 x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
263                 if dir == rows {
264                         if y1 == num && y2 == num && offset < 0 {
265                                 f.deleteMergeCell(ws, i)
266                                 i--
267                         }
268                         y1 = f.adjustMergeCellsHelper(y1, num, offset)
269                         y2 = f.adjustMergeCellsHelper(y2, num, offset)
270                 } else {
271                         if x1 == num && x2 == num && offset < 0 {
272                                 f.deleteMergeCell(ws, i)
273                                 i--
274                         }
275                         x1 = f.adjustMergeCellsHelper(x1, num, offset)
276                         x2 = f.adjustMergeCellsHelper(x2, num, offset)
277                 }
278                 if x1 == x2 && y1 == y2 {
279                         f.deleteMergeCell(ws, i)
280                         i--
281                 }
282                 if areaData.Ref, err = f.coordinatesToAreaRef([]int{x1, y1, x2, y2}); err != nil {
283                         return err
284                 }
285         }
286         return nil
287 }
288
289 // adjustMergeCellsHelper provides a function for adjusting merge cells to
290 // compare and calculate cell axis by the given pivot, operation axis and
291 // offset.
292 func (f *File) adjustMergeCellsHelper(pivot, num, offset int) int {
293         if pivot >= num {
294                 pivot += offset
295                 if pivot < 1 {
296                         return 1
297                 }
298                 return pivot
299         }
300         return pivot
301 }
302
303 // deleteMergeCell provides a function to delete merged cell by given index.
304 func (f *File) deleteMergeCell(ws *xlsxWorksheet, idx int) {
305         if len(ws.MergeCells.Cells) > idx {
306                 ws.MergeCells.Cells = append(ws.MergeCells.Cells[:idx], ws.MergeCells.Cells[idx+1:]...)
307                 ws.MergeCells.Count = len(ws.MergeCells.Cells)
308         }
309 }
310
311 // adjustCalcChain provides a function to update the calculation chain when
312 // inserting or deleting rows or columns.
313 func (f *File) adjustCalcChain(dir adjustDirection, num, offset int) error {
314         if f.CalcChain == nil {
315                 return nil
316         }
317         for index, c := range f.CalcChain.C {
318                 colNum, rowNum, err := CellNameToCoordinates(c.R)
319                 if err != nil {
320                         return err
321                 }
322                 if dir == rows && num <= rowNum {
323                         if newRow := rowNum + offset; newRow > 0 {
324                                 f.CalcChain.C[index].R, _ = CoordinatesToCellName(colNum, newRow)
325                         }
326                 }
327                 if dir == columns && num <= colNum {
328                         if newCol := colNum + offset; newCol > 0 {
329                                 f.CalcChain.C[index].R, _ = CoordinatesToCellName(newCol, rowNum)
330                         }
331                 }
332         }
333         return nil
334 }