OSDN Git Service

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