OSDN Git Service

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