OSDN Git Service

This closes #1125, support update drawing objects on inserting/deleting columns/rows...
[excelize/excelize.git] / adjust.go
1 // Copyright 2016 - 2023 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 and
6 // read from XLAM / XLSM / XLSX / XLTM / XLTX files. Supports reading and
7 // writing spreadsheet documents generated by Microsoft Excelâ„¢ 2007 and later.
8 // Supports complex components by high compatibility, and provided streaming
9 // API for generating or reading data from a worksheet with huge amounts of
10 // data. This library needs Go version 1.16 or later.
11
12 package excelize
13
14 import (
15         "bytes"
16         "encoding/xml"
17         "io"
18         "strconv"
19         "strings"
20         "unicode"
21
22         "github.com/xuri/efp"
23 )
24
25 type adjustDirection bool
26
27 const (
28         columns adjustDirection = false
29         rows    adjustDirection = true
30 )
31
32 // adjustHelperFunc defines functions to adjust helper.
33 var adjustHelperFunc = [6]func(*File, *xlsxWorksheet, string, adjustDirection, int, int, int) error{
34         func(f *File, ws *xlsxWorksheet, sheet string, dir adjustDirection, num, offset, sheetID int) error {
35                 return f.adjustTable(ws, sheet, dir, num, offset, sheetID)
36         },
37         func(f *File, ws *xlsxWorksheet, sheet string, dir adjustDirection, num, offset, sheetID int) error {
38                 return f.adjustMergeCells(ws, sheet, dir, num, offset, sheetID)
39         },
40         func(f *File, ws *xlsxWorksheet, sheet string, dir adjustDirection, num, offset, sheetID int) error {
41                 return f.adjustAutoFilter(ws, sheet, dir, num, offset, sheetID)
42         },
43         func(f *File, ws *xlsxWorksheet, sheet string, dir adjustDirection, num, offset, sheetID int) error {
44                 return f.adjustCalcChain(ws, sheet, dir, num, offset, sheetID)
45         },
46         func(f *File, ws *xlsxWorksheet, sheet string, dir adjustDirection, num, offset, sheetID int) error {
47                 return f.adjustVolatileDeps(ws, sheet, dir, num, offset, sheetID)
48         },
49         func(f *File, ws *xlsxWorksheet, sheet string, dir adjustDirection, num, offset, sheetID int) error {
50                 return f.adjustDrawings(ws, sheet, dir, num, offset, sheetID)
51         },
52 }
53
54 // adjustHelper provides a function to adjust rows and columns dimensions,
55 // hyperlinks, merged cells and auto filter when inserting or deleting rows or
56 // columns.
57 //
58 // sheet: Worksheet name that we're editing
59 // column: Index number of the column we're inserting/deleting before
60 // row: Index number of the row we're inserting/deleting before
61 // offset: Number of rows/column to insert/delete negative values indicate deletion
62 //
63 // TODO: adjustComments, adjustDataValidations, adjustDrawings, adjustPageBreaks, adjustProtectedCells
64 func (f *File) adjustHelper(sheet string, dir adjustDirection, num, offset int) error {
65         ws, err := f.workSheetReader(sheet)
66         if err != nil {
67                 return err
68         }
69         sheetID := f.getSheetID(sheet)
70         if dir == rows {
71                 err = f.adjustRowDimensions(sheet, ws, num, offset)
72         } else {
73                 err = f.adjustColDimensions(sheet, ws, num, offset)
74         }
75         if err != nil {
76                 return err
77         }
78         f.adjustHyperlinks(ws, sheet, dir, num, offset)
79         ws.checkSheet()
80         _ = ws.checkRow()
81         for _, fn := range adjustHelperFunc {
82                 if err := fn(f, ws, sheet, dir, num, offset, sheetID); err != nil {
83                         return err
84                 }
85         }
86         if ws.MergeCells != nil && len(ws.MergeCells.Cells) == 0 {
87                 ws.MergeCells = nil
88         }
89         return nil
90 }
91
92 // adjustCols provides a function to update column style when inserting or
93 // deleting columns.
94 func (f *File) adjustCols(ws *xlsxWorksheet, col, offset int) error {
95         if ws.Cols == nil {
96                 return nil
97         }
98         for i := 0; i < len(ws.Cols.Col); i++ {
99                 if offset > 0 {
100                         if ws.Cols.Col[i].Max+1 == col {
101                                 ws.Cols.Col[i].Max += offset
102                                 continue
103                         }
104                         if ws.Cols.Col[i].Min >= col {
105                                 ws.Cols.Col[i].Min += offset
106                                 ws.Cols.Col[i].Max += offset
107                                 continue
108                         }
109                         if ws.Cols.Col[i].Min < col && ws.Cols.Col[i].Max >= col {
110                                 ws.Cols.Col[i].Max += offset
111                         }
112                 }
113                 if offset < 0 {
114                         if ws.Cols.Col[i].Min == col && ws.Cols.Col[i].Max == col {
115                                 if len(ws.Cols.Col) > 1 {
116                                         ws.Cols.Col = append(ws.Cols.Col[:i], ws.Cols.Col[i+1:]...)
117                                 } else {
118                                         ws.Cols.Col = nil
119                                 }
120                                 i--
121                                 continue
122                         }
123                         if ws.Cols.Col[i].Min > col {
124                                 ws.Cols.Col[i].Min += offset
125                                 ws.Cols.Col[i].Max += offset
126                                 continue
127                         }
128                         if ws.Cols.Col[i].Min <= col && ws.Cols.Col[i].Max >= col {
129                                 ws.Cols.Col[i].Max += offset
130                         }
131                 }
132         }
133         return nil
134 }
135
136 // adjustColDimensions provides a function to update column dimensions when
137 // inserting or deleting rows or columns.
138 func (f *File) adjustColDimensions(sheet string, ws *xlsxWorksheet, col, offset int) error {
139         for rowIdx := range ws.SheetData.Row {
140                 for _, v := range ws.SheetData.Row[rowIdx].C {
141                         if cellCol, _, _ := CellNameToCoordinates(v.R); col <= cellCol {
142                                 if newCol := cellCol + offset; newCol > 0 && newCol > MaxColumns {
143                                         return ErrColumnNumber
144                                 }
145                         }
146                 }
147         }
148         for _, sheetN := range f.GetSheetList() {
149                 worksheet, err := f.workSheetReader(sheetN)
150                 if err != nil {
151                         if err.Error() == newNotWorksheetError(sheetN).Error() {
152                                 continue
153                         }
154                         return err
155                 }
156                 for rowIdx := range worksheet.SheetData.Row {
157                         for colIdx, v := range worksheet.SheetData.Row[rowIdx].C {
158                                 if cellCol, cellRow, _ := CellNameToCoordinates(v.R); sheetN == sheet && col <= cellCol {
159                                         if newCol := cellCol + offset; newCol > 0 {
160                                                 worksheet.SheetData.Row[rowIdx].C[colIdx].R, _ = CoordinatesToCellName(newCol, cellRow)
161                                         }
162                                 }
163                                 if err := f.adjustFormula(sheet, sheetN, worksheet.SheetData.Row[rowIdx].C[colIdx].F, columns, col, offset, false); err != nil {
164                                         return err
165                                 }
166                         }
167                 }
168         }
169         return f.adjustCols(ws, col, offset)
170 }
171
172 // adjustRowDimensions provides a function to update row dimensions when
173 // inserting or deleting rows or columns.
174 func (f *File) adjustRowDimensions(sheet string, ws *xlsxWorksheet, row, offset int) error {
175         for _, sheetN := range f.GetSheetList() {
176                 if sheetN == sheet {
177                         continue
178                 }
179                 worksheet, err := f.workSheetReader(sheetN)
180                 if err != nil {
181                         if err.Error() == newNotWorksheetError(sheetN).Error() {
182                                 continue
183                         }
184                         return err
185                 }
186                 numOfRows := len(worksheet.SheetData.Row)
187                 for i := 0; i < numOfRows; i++ {
188                         r := &worksheet.SheetData.Row[i]
189                         if err = f.adjustSingleRowFormulas(sheet, sheetN, r, row, offset, false); err != nil {
190                                 return err
191                         }
192                 }
193         }
194         totalRows := len(ws.SheetData.Row)
195         if totalRows == 0 {
196                 return nil
197         }
198         lastRow := &ws.SheetData.Row[totalRows-1]
199         if newRow := lastRow.R + offset; lastRow.R >= row && newRow > 0 && newRow > TotalRows {
200                 return ErrMaxRows
201         }
202         numOfRows := len(ws.SheetData.Row)
203         for i := 0; i < numOfRows; i++ {
204                 r := &ws.SheetData.Row[i]
205                 if newRow := r.R + offset; r.R >= row && newRow > 0 {
206                         r.adjustSingleRowDimensions(offset)
207                 }
208                 if err := f.adjustSingleRowFormulas(sheet, sheet, r, row, offset, false); err != nil {
209                         return err
210                 }
211         }
212         return nil
213 }
214
215 // adjustSingleRowDimensions provides a function to adjust single row dimensions.
216 func (r *xlsxRow) adjustSingleRowDimensions(offset int) {
217         r.R += offset
218         for i, col := range r.C {
219                 colName, _, _ := SplitCellName(col.R)
220                 r.C[i].R, _ = JoinCellName(colName, r.R)
221         }
222 }
223
224 // adjustSingleRowFormulas provides a function to adjust single row formulas.
225 func (f *File) adjustSingleRowFormulas(sheet, sheetN string, r *xlsxRow, num, offset int, si bool) error {
226         for _, col := range r.C {
227                 if err := f.adjustFormula(sheet, sheetN, col.F, rows, num, offset, si); err != nil {
228                         return err
229                 }
230         }
231         return nil
232 }
233
234 // adjustCellRef provides a function to adjust cell reference.
235 func (f *File) adjustCellRef(ref string, dir adjustDirection, num, offset int) (string, error) {
236         if !strings.Contains(ref, ":") {
237                 ref += ":" + ref
238         }
239         coordinates, err := rangeRefToCoordinates(ref)
240         if err != nil {
241                 return ref, err
242         }
243         if dir == columns {
244                 if coordinates[0] >= num {
245                         coordinates[0] += offset
246                 }
247                 if coordinates[2] >= num {
248                         coordinates[2] += offset
249                 }
250         } else {
251                 if coordinates[1] >= num {
252                         coordinates[1] += offset
253                 }
254                 if coordinates[3] >= num {
255                         coordinates[3] += offset
256                 }
257         }
258         return f.coordinatesToRangeRef(coordinates)
259 }
260
261 // adjustFormula provides a function to adjust formula reference and shared
262 // formula reference.
263 func (f *File) adjustFormula(sheet, sheetN string, formula *xlsxF, dir adjustDirection, num, offset int, si bool) error {
264         if formula == nil {
265                 return nil
266         }
267         var err error
268         if formula.Ref != "" && sheet == sheetN {
269                 if formula.Ref, err = f.adjustCellRef(formula.Ref, dir, num, offset); err != nil {
270                         return err
271                 }
272                 if si && formula.Si != nil {
273                         formula.Si = intPtr(*formula.Si + 1)
274                 }
275         }
276         if formula.Content != "" {
277                 if formula.Content, err = f.adjustFormulaRef(sheet, sheetN, formula.Content, dir, num, offset); err != nil {
278                         return err
279                 }
280         }
281         return nil
282 }
283
284 // isFunctionStop provides a function to check if token is a function stop.
285 func isFunctionStop(token efp.Token) bool {
286         return token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStop
287 }
288
289 // isFunctionStart provides a function to check if token is a function start.
290 func isFunctionStart(token efp.Token) bool {
291         return token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStart
292 }
293
294 // escapeSheetName enclose sheet name in single quotation marks if the giving
295 // worksheet name includes spaces or non-alphabetical characters.
296 func escapeSheetName(name string) string {
297         if strings.IndexFunc(name, func(r rune) bool {
298                 return !unicode.IsLetter(r) && !unicode.IsNumber(r)
299         }) != -1 {
300                 return string(efp.QuoteSingle) + name + string(efp.QuoteSingle)
301         }
302         return name
303 }
304
305 // adjustFormulaColumnName adjust column name in the formula reference.
306 func adjustFormulaColumnName(name string, dir adjustDirection, num, offset int) (string, error) {
307         col, err := ColumnNameToNumber(name)
308         if err != nil {
309                 return name, err
310         }
311         if dir == columns && col >= num {
312                 col += offset
313                 return ColumnNumberToName(col)
314         }
315         return name, nil
316 }
317
318 // adjustFormulaRowNumber adjust row number in the formula reference.
319 func adjustFormulaRowNumber(name string, dir adjustDirection, num, offset int) (string, error) {
320         row, _ := strconv.Atoi(name)
321         if dir == rows && row >= num {
322                 row += offset
323                 if row > TotalRows {
324                         return name, ErrMaxRows
325                 }
326                 return strconv.Itoa(row), nil
327         }
328         return name, nil
329 }
330
331 // adjustFormulaOperandRef adjust cell reference in the operand tokens for the formula.
332 func adjustFormulaOperandRef(row, col, operand string, dir adjustDirection, num int, offset int) (string, string, string, error) {
333         if col != "" {
334                 name, err := adjustFormulaColumnName(col, dir, num, offset)
335                 if err != nil {
336                         return row, col, operand, err
337                 }
338                 operand += name
339                 col = ""
340         }
341         if row != "" {
342                 name, err := adjustFormulaRowNumber(row, dir, num, offset)
343                 if err != nil {
344                         return row, col, operand, err
345                 }
346                 operand += name
347                 row = ""
348         }
349         return row, col, operand, nil
350 }
351
352 // adjustFormulaOperand adjust range operand tokens for the formula.
353 func (f *File) adjustFormulaOperand(sheet, sheetN string, token efp.Token, dir adjustDirection, num int, offset int) (string, error) {
354         var (
355                 err                          error
356                 sheetName, col, row, operand string
357                 cell                         = token.TValue
358                 tokens                       = strings.Split(token.TValue, "!")
359         )
360         if len(tokens) == 2 { // have a worksheet
361                 sheetName, cell = tokens[0], tokens[1]
362                 operand = escapeSheetName(sheetName) + "!"
363         }
364         if sheet != sheetN && sheet != sheetName {
365                 return operand + cell, err
366         }
367         for _, r := range cell {
368                 if ('A' <= r && r <= 'Z') || ('a' <= r && r <= 'z') {
369                         col += string(r)
370                         continue
371                 }
372                 if '0' <= r && r <= '9' {
373                         row += string(r)
374                         if col != "" {
375                                 name, err := adjustFormulaColumnName(col, dir, num, offset)
376                                 if err != nil {
377                                         return operand, err
378                                 }
379                                 operand += name
380                                 col = ""
381                         }
382                         continue
383                 }
384                 if row, col, operand, err = adjustFormulaOperandRef(row, col, operand, dir, num, offset); err != nil {
385                         return operand, err
386                 }
387                 operand += string(r)
388         }
389         _, _, operand, err = adjustFormulaOperandRef(row, col, operand, dir, num, offset)
390         return operand, err
391 }
392
393 // adjustFormulaRef returns adjusted formula by giving adjusting direction and
394 // the base number of column or row, and offset.
395 func (f *File) adjustFormulaRef(sheet, sheetN, formula string, dir adjustDirection, num, offset int) (string, error) {
396         var (
397                 val          string
398                 definedNames []string
399                 ps           = efp.ExcelParser()
400         )
401         for _, definedName := range f.GetDefinedName() {
402                 if definedName.Scope == "Workbook" || definedName.Scope == sheet {
403                         definedNames = append(definedNames, definedName.Name)
404                 }
405         }
406         for _, token := range ps.Parse(formula) {
407                 if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeRange {
408                         if inStrSlice(definedNames, token.TValue, true) != -1 {
409                                 val += token.TValue
410                                 continue
411                         }
412                         if strings.ContainsAny(token.TValue, "[]") {
413                                 val += token.TValue
414                                 continue
415                         }
416                         operand, err := f.adjustFormulaOperand(sheet, sheetN, token, dir, num, offset)
417                         if err != nil {
418                                 return val, err
419                         }
420                         val += operand
421                         continue
422                 }
423                 if isFunctionStart(token) {
424                         val += token.TValue + string(efp.ParenOpen)
425                         continue
426                 }
427                 if isFunctionStop(token) {
428                         val += token.TValue + string(efp.ParenClose)
429                         continue
430                 }
431                 if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeText {
432                         val += string(efp.QuoteDouble) + strings.ReplaceAll(token.TValue, "\"", "\"\"") + string(efp.QuoteDouble)
433                         continue
434                 }
435                 val += token.TValue
436         }
437         return val, nil
438 }
439
440 // adjustHyperlinks provides a function to update hyperlinks when inserting or
441 // deleting rows or columns.
442 func (f *File) adjustHyperlinks(ws *xlsxWorksheet, sheet string, dir adjustDirection, num, offset int) {
443         // short path
444         if ws.Hyperlinks == nil || len(ws.Hyperlinks.Hyperlink) == 0 {
445                 return
446         }
447
448         // order is important
449         if offset < 0 {
450                 for i := len(ws.Hyperlinks.Hyperlink) - 1; i >= 0; i-- {
451                         linkData := ws.Hyperlinks.Hyperlink[i]
452                         colNum, rowNum, _ := CellNameToCoordinates(linkData.Ref)
453
454                         if (dir == rows && num == rowNum) || (dir == columns && num == colNum) {
455                                 f.deleteSheetRelationships(sheet, linkData.RID)
456                                 if len(ws.Hyperlinks.Hyperlink) > 1 {
457                                         ws.Hyperlinks.Hyperlink = append(ws.Hyperlinks.Hyperlink[:i],
458                                                 ws.Hyperlinks.Hyperlink[i+1:]...)
459                                 } else {
460                                         ws.Hyperlinks = nil
461                                 }
462                         }
463                 }
464         }
465         if ws.Hyperlinks == nil {
466                 return
467         }
468         for i := range ws.Hyperlinks.Hyperlink {
469                 link := &ws.Hyperlinks.Hyperlink[i] // get reference
470                 link.Ref, _ = f.adjustFormulaRef(sheet, sheet, link.Ref, dir, num, offset)
471         }
472 }
473
474 // adjustTable provides a function to update the table when inserting or
475 // deleting rows or columns.
476 func (f *File) adjustTable(ws *xlsxWorksheet, sheet string, dir adjustDirection, num, offset, sheetID int) error {
477         if ws.TableParts == nil || len(ws.TableParts.TableParts) == 0 {
478                 return nil
479         }
480         for idx := 0; idx < len(ws.TableParts.TableParts); idx++ {
481                 tbl := ws.TableParts.TableParts[idx]
482                 target := f.getSheetRelationshipsTargetByID(sheet, tbl.RID)
483                 tableXML := strings.ReplaceAll(target, "..", "xl")
484                 content, ok := f.Pkg.Load(tableXML)
485                 if !ok {
486                         continue
487                 }
488                 t := xlsxTable{}
489                 if err := f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(content.([]byte)))).
490                         Decode(&t); err != nil && err != io.EOF {
491                         return nil
492                 }
493                 coordinates, err := rangeRefToCoordinates(t.Ref)
494                 if err != nil {
495                         return err
496                 }
497                 // Remove the table when deleting the header row of the table
498                 if dir == rows && num == coordinates[0] && offset == -1 {
499                         ws.TableParts.TableParts = append(ws.TableParts.TableParts[:idx], ws.TableParts.TableParts[idx+1:]...)
500                         ws.TableParts.Count = len(ws.TableParts.TableParts)
501                         idx--
502                         continue
503                 }
504                 coordinates = f.adjustAutoFilterHelper(dir, coordinates, num, offset)
505                 x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
506                 if y2-y1 < 1 || x2-x1 < 0 {
507                         ws.TableParts.TableParts = append(ws.TableParts.TableParts[:idx], ws.TableParts.TableParts[idx+1:]...)
508                         ws.TableParts.Count = len(ws.TableParts.TableParts)
509                         idx--
510                         continue
511                 }
512                 t.Ref, _ = f.coordinatesToRangeRef([]int{x1, y1, x2, y2})
513                 if t.AutoFilter != nil {
514                         t.AutoFilter.Ref = t.Ref
515                 }
516                 _ = f.setTableColumns(sheet, true, x1, y1, x2, &t)
517                 // Currently doesn't support query table
518                 t.TableType, t.TotalsRowCount, t.ConnectionID = "", 0, 0
519                 table, _ := xml.Marshal(t)
520                 f.saveFileList(tableXML, table)
521         }
522         return nil
523 }
524
525 // adjustAutoFilter provides a function to update the auto filter when
526 // inserting or deleting rows or columns.
527 func (f *File) adjustAutoFilter(ws *xlsxWorksheet, sheet string, dir adjustDirection, num, offset, sheetID int) error {
528         if ws.AutoFilter == nil {
529                 return nil
530         }
531
532         coordinates, err := rangeRefToCoordinates(ws.AutoFilter.Ref)
533         if err != nil {
534                 return err
535         }
536         x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
537
538         if (dir == rows && y1 == num && offset < 0) || (dir == columns && x1 == num && x2 == num) {
539                 ws.AutoFilter = nil
540                 for rowIdx := range ws.SheetData.Row {
541                         rowData := &ws.SheetData.Row[rowIdx]
542                         if rowData.R > y1 && rowData.R <= y2 {
543                                 rowData.Hidden = false
544                         }
545                 }
546                 return err
547         }
548
549         coordinates = f.adjustAutoFilterHelper(dir, coordinates, num, offset)
550         x1, y1, x2, y2 = coordinates[0], coordinates[1], coordinates[2], coordinates[3]
551
552         ws.AutoFilter.Ref, err = f.coordinatesToRangeRef([]int{x1, y1, x2, y2})
553         return err
554 }
555
556 // adjustAutoFilterHelper provides a function for adjusting auto filter to
557 // compare and calculate cell reference by the giving adjusting direction,
558 // operation reference and offset.
559 func (f *File) adjustAutoFilterHelper(dir adjustDirection, coordinates []int, num, offset int) []int {
560         if dir == rows {
561                 if coordinates[1] >= num {
562                         coordinates[1] += offset
563                 }
564                 if coordinates[3] >= num {
565                         coordinates[3] += offset
566                 }
567                 return coordinates
568         }
569         if coordinates[0] >= num {
570                 coordinates[0] += offset
571         }
572         if coordinates[2] >= num {
573                 coordinates[2] += offset
574         }
575         return coordinates
576 }
577
578 // adjustMergeCells provides a function to update merged cells when inserting
579 // or deleting rows or columns.
580 func (f *File) adjustMergeCells(ws *xlsxWorksheet, sheet string, dir adjustDirection, num, offset, sheetID int) error {
581         if ws.MergeCells == nil {
582                 return nil
583         }
584
585         for i := 0; i < len(ws.MergeCells.Cells); i++ {
586                 mergedCells := ws.MergeCells.Cells[i]
587                 mergedCellsRef := mergedCells.Ref
588                 if !strings.Contains(mergedCellsRef, ":") {
589                         mergedCellsRef += ":" + mergedCellsRef
590                 }
591                 coordinates, err := rangeRefToCoordinates(mergedCellsRef)
592                 if err != nil {
593                         return err
594                 }
595                 x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
596                 if dir == rows {
597                         if y1 == num && y2 == num && offset < 0 {
598                                 f.deleteMergeCell(ws, i)
599                                 continue
600                         }
601
602                         y1, y2 = f.adjustMergeCellsHelper(y1, y2, num, offset)
603                 } else {
604                         if x1 == num && x2 == num && offset < 0 {
605                                 f.deleteMergeCell(ws, i)
606                                 continue
607                         }
608
609                         x1, x2 = f.adjustMergeCellsHelper(x1, x2, num, offset)
610                 }
611                 if x1 == x2 && y1 == y2 {
612                         f.deleteMergeCell(ws, i)
613                         i--
614                         continue
615                 }
616                 mergedCells.rect = []int{x1, y1, x2, y2}
617                 if mergedCells.Ref, err = f.coordinatesToRangeRef([]int{x1, y1, x2, y2}); err != nil {
618                         return err
619                 }
620         }
621         return nil
622 }
623
624 // adjustMergeCellsHelper provides a function for adjusting merge cells to
625 // compare and calculate cell reference by the given pivot, operation reference and
626 // offset.
627 func (f *File) adjustMergeCellsHelper(p1, p2, num, offset int) (int, int) {
628         if p2 < p1 {
629                 p1, p2 = p2, p1
630         }
631
632         if offset >= 0 {
633                 if num <= p1 {
634                         p1 += offset
635                         p2 += offset
636                 } else if num <= p2 {
637                         p2 += offset
638                 }
639                 return p1, p2
640         }
641         if num < p1 || (num == p1 && num == p2) {
642                 p1 += offset
643                 p2 += offset
644         } else if num <= p2 {
645                 p2 += offset
646         }
647         return p1, p2
648 }
649
650 // deleteMergeCell provides a function to delete merged cell by given index.
651 func (f *File) deleteMergeCell(ws *xlsxWorksheet, idx int) {
652         if idx < 0 {
653                 return
654         }
655         if len(ws.MergeCells.Cells) > idx {
656                 ws.MergeCells.Cells = append(ws.MergeCells.Cells[:idx], ws.MergeCells.Cells[idx+1:]...)
657                 ws.MergeCells.Count = len(ws.MergeCells.Cells)
658         }
659 }
660
661 // adjustCellName returns updated cell name by giving column/row number and
662 // offset on inserting or deleting rows or columns.
663 func adjustCellName(cell string, dir adjustDirection, c, r, offset int) (string, error) {
664         if dir == rows {
665                 if rn := r + offset; rn > 0 {
666                         return CoordinatesToCellName(c, rn)
667                 }
668         }
669         return CoordinatesToCellName(c+offset, r)
670 }
671
672 // adjustCalcChain provides a function to update the calculation chain when
673 // inserting or deleting rows or columns.
674 func (f *File) adjustCalcChain(ws *xlsxWorksheet, sheet string, dir adjustDirection, num, offset, sheetID int) error {
675         if f.CalcChain == nil {
676                 return nil
677         }
678         // If sheet ID is omitted, it is assumed to be the same as the i value of
679         // the previous cell.
680         var prevSheetID int
681         for i := 0; i < len(f.CalcChain.C); i++ {
682                 c := f.CalcChain.C[i]
683                 if c.I == 0 {
684                         c.I = prevSheetID
685                 }
686                 prevSheetID = c.I
687                 if c.I != sheetID {
688                         continue
689                 }
690                 colNum, rowNum, err := CellNameToCoordinates(c.R)
691                 if err != nil {
692                         return err
693                 }
694                 if dir == rows && num <= rowNum {
695                         if num == rowNum && offset == -1 {
696                                 _ = f.deleteCalcChain(c.I, c.R)
697                                 i--
698                                 continue
699                         }
700                         f.CalcChain.C[i].R, _ = adjustCellName(c.R, dir, colNum, rowNum, offset)
701                 }
702                 if dir == columns && num <= colNum {
703                         if num == colNum && offset == -1 {
704                                 _ = f.deleteCalcChain(c.I, c.R)
705                                 i--
706                                 continue
707                         }
708                         f.CalcChain.C[i].R, _ = adjustCellName(c.R, dir, colNum, rowNum, offset)
709                 }
710         }
711         return nil
712 }
713
714 // adjustVolatileDepsTopic updates the volatile dependencies topic when
715 // inserting or deleting rows or columns.
716 func (vt *xlsxVolTypes) adjustVolatileDepsTopic(cell string, dir adjustDirection, indexes []int) (int, error) {
717         num, offset, i1, i2, i3, i4 := indexes[0], indexes[1], indexes[2], indexes[3], indexes[4], indexes[5]
718         colNum, rowNum, err := CellNameToCoordinates(cell)
719         if err != nil {
720                 return i4, err
721         }
722         if dir == rows && num <= rowNum {
723                 if num == rowNum && offset == -1 {
724                         vt.deleteVolTopicRef(i1, i2, i3, i4)
725                         i4--
726                         return i4, err
727                 }
728                 vt.VolType[i1].Main[i2].Tp[i3].Tr[i4].R, _ = adjustCellName(cell, dir, colNum, rowNum, offset)
729         }
730         if dir == columns && num <= colNum {
731                 if num == colNum && offset == -1 {
732                         vt.deleteVolTopicRef(i1, i2, i3, i4)
733                         i4--
734                         return i4, err
735                 }
736                 if name, _ := adjustCellName(cell, dir, colNum, rowNum, offset); name != "" {
737                         vt.VolType[i1].Main[i2].Tp[i3].Tr[i4].R, _ = adjustCellName(cell, dir, colNum, rowNum, offset)
738                 }
739         }
740         return i4, err
741 }
742
743 // adjustVolatileDeps updates the volatile dependencies when inserting or
744 // deleting rows or columns.
745 func (f *File) adjustVolatileDeps(ws *xlsxWorksheet, sheet string, dir adjustDirection, num, offset, sheetID int) error {
746         volTypes, err := f.volatileDepsReader()
747         if err != nil || volTypes == nil {
748                 return err
749         }
750         for i1 := 0; i1 < len(volTypes.VolType); i1++ {
751                 for i2 := 0; i2 < len(volTypes.VolType[i1].Main); i2++ {
752                         for i3 := 0; i3 < len(volTypes.VolType[i1].Main[i2].Tp); i3++ {
753                                 for i4 := 0; i4 < len(volTypes.VolType[i1].Main[i2].Tp[i3].Tr); i4++ {
754                                         ref := volTypes.VolType[i1].Main[i2].Tp[i3].Tr[i4]
755                                         if ref.S != sheetID {
756                                                 continue
757                                         }
758                                         if i4, err = volTypes.adjustVolatileDepsTopic(ref.R, dir, []int{num, offset, i1, i2, i3, i4}); err != nil {
759                                                 return err
760                                         }
761                                 }
762                         }
763                 }
764         }
765         return nil
766 }
767
768 // adjustDrawings updates the starting anchor of the two cell anchor pictures
769 // and charts object when inserting or deleting rows or columns.
770 func (from *xlsxFrom) adjustDrawings(dir adjustDirection, num, offset int, editAs string) (bool, error) {
771         var ok bool
772         if dir == columns && from.Col+1 >= num && from.Col+offset >= 0 {
773                 if from.Col+offset >= MaxColumns {
774                         return false, ErrColumnNumber
775                 }
776                 from.Col += offset
777                 ok = editAs == "oneCell"
778         }
779         if dir == rows && from.Row+1 >= num && from.Row+offset >= 0 {
780                 if from.Row+offset >= TotalRows {
781                         return false, ErrMaxRows
782                 }
783                 from.Row += offset
784                 ok = editAs == "oneCell"
785         }
786         return ok, nil
787 }
788
789 // adjustDrawings updates the ending anchor of the two cell anchor pictures
790 // and charts object when inserting or deleting rows or columns.
791 func (to *xlsxTo) adjustDrawings(dir adjustDirection, num, offset int, editAs string, ok bool) error {
792         if dir == columns && to.Col+1 >= num && to.Col+offset >= 0 && ok {
793                 if to.Col+offset >= MaxColumns {
794                         return ErrColumnNumber
795                 }
796                 to.Col += offset
797         }
798         if dir == rows && to.Row+1 >= num && to.Row+offset >= 0 && ok {
799                 if to.Row+offset >= TotalRows {
800                         return ErrMaxRows
801                 }
802                 to.Row += offset
803         }
804         return nil
805 }
806
807 // adjustDrawings updates the two cell anchor pictures and charts object when
808 // inserting or deleting rows or columns.
809 func (a *xdrCellAnchor) adjustDrawings(dir adjustDirection, num, offset int) error {
810         editAs := a.EditAs
811         if a.From == nil || a.To == nil || editAs == "absolute" {
812                 return nil
813         }
814         ok, err := a.From.adjustDrawings(dir, num, offset, editAs)
815         if err != nil {
816                 return err
817         }
818         return a.To.adjustDrawings(dir, num, offset, editAs, ok || editAs == "")
819 }
820
821 // adjustDrawings updates the existing two cell anchor pictures and charts
822 // object when inserting or deleting rows or columns.
823 func (a *xlsxCellAnchorPos) adjustDrawings(dir adjustDirection, num, offset int, editAs string) error {
824         if a.From == nil || a.To == nil || editAs == "absolute" {
825                 return nil
826         }
827         ok, err := a.From.adjustDrawings(dir, num, offset, editAs)
828         if err != nil {
829                 return err
830         }
831         return a.To.adjustDrawings(dir, num, offset, editAs, ok || editAs == "")
832 }
833
834 // adjustDrawings updates the pictures and charts object when inserting or
835 // deleting rows or columns.
836 func (f *File) adjustDrawings(ws *xlsxWorksheet, sheet string, dir adjustDirection, num, offset, sheetID int) error {
837         if ws.Drawing == nil {
838                 return nil
839         }
840         target := f.getSheetRelationshipsTargetByID(sheet, ws.Drawing.RID)
841         drawingXML := strings.TrimPrefix(strings.ReplaceAll(target, "..", "xl"), "/")
842         var (
843                 err  error
844                 wsDr *xlsxWsDr
845         )
846         if wsDr, _, err = f.drawingParser(drawingXML); err != nil {
847                 return err
848         }
849         anchorCb := func(a *xdrCellAnchor) error {
850                 if a.GraphicFrame == "" {
851                         return a.adjustDrawings(dir, num, offset)
852                 }
853                 deCellAnchor := decodeCellAnchor{}
854                 deCellAnchorPos := decodeCellAnchorPos{}
855                 _ = f.xmlNewDecoder(strings.NewReader("<decodeCellAnchor>" + a.GraphicFrame + "</decodeCellAnchor>")).Decode(&deCellAnchor)
856                 _ = f.xmlNewDecoder(strings.NewReader("<decodeCellAnchorPos>" + a.GraphicFrame + "</decodeCellAnchorPos>")).Decode(&deCellAnchorPos)
857                 xlsxCellAnchorPos := xlsxCellAnchorPos(deCellAnchorPos)
858                 for i := 0; i < len(xlsxCellAnchorPos.AlternateContent); i++ {
859                         xlsxCellAnchorPos.AlternateContent[i].XMLNSMC = SourceRelationshipCompatibility.Value
860                 }
861                 if deCellAnchor.From != nil {
862                         xlsxCellAnchorPos.From = &xlsxFrom{
863                                 Col: deCellAnchor.From.Col, ColOff: deCellAnchor.From.ColOff,
864                                 Row: deCellAnchor.From.Row, RowOff: deCellAnchor.From.RowOff,
865                         }
866                 }
867                 if deCellAnchor.To != nil {
868                         xlsxCellAnchorPos.To = &xlsxTo{
869                                 Col: deCellAnchor.To.Col, ColOff: deCellAnchor.To.ColOff,
870                                 Row: deCellAnchor.To.Row, RowOff: deCellAnchor.To.RowOff,
871                         }
872                 }
873                 if err = xlsxCellAnchorPos.adjustDrawings(dir, num, offset, a.EditAs); err != nil {
874                         return err
875                 }
876                 cellAnchor, _ := xml.Marshal(xlsxCellAnchorPos)
877                 a.GraphicFrame = strings.TrimSuffix(strings.TrimPrefix(string(cellAnchor), "<xlsxCellAnchorPos>"), "</xlsxCellAnchorPos>")
878                 return err
879         }
880         for _, anchor := range wsDr.TwoCellAnchor {
881                 if err = anchorCb(anchor); err != nil {
882                         return err
883                 }
884         }
885         return nil
886 }