OSDN Git Service

Stream to Excel table (#530)
[excelize/excelize.git] / adjust.go
1 // Copyright 2016 - 2019 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 func sortCoordinates(coordinates []int) error {
217         if len(coordinates) != 4 {
218                 return errors.New("coordinates length must be 4")
219         }
220         if coordinates[2] < coordinates[0] {
221                 coordinates[2], coordinates[0] = coordinates[0], coordinates[2]
222         }
223         if coordinates[3] < coordinates[1] {
224                 coordinates[3], coordinates[1] = coordinates[1], coordinates[3]
225         }
226         return nil
227 }
228
229 // coordinatesToAreaRef provides a function to convert a pair of coordinates
230 // to area reference.
231 func (f *File) coordinatesToAreaRef(coordinates []int) (string, error) {
232         if len(coordinates) != 4 {
233                 return "", errors.New("coordinates length must be 4")
234         }
235         firstCell, err := CoordinatesToCellName(coordinates[0], coordinates[1])
236         if err != nil {
237                 return "", err
238         }
239         lastCell, err := CoordinatesToCellName(coordinates[2], coordinates[3])
240         if err != nil {
241                 return "", err
242         }
243         return firstCell + ":" + lastCell, err
244 }
245
246 // adjustMergeCells provides a function to update merged cells when inserting
247 // or deleting rows or columns.
248 func (f *File) adjustMergeCells(xlsx *xlsxWorksheet, dir adjustDirection, num, offset int) error {
249         if xlsx.MergeCells == nil {
250                 return nil
251         }
252
253         for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
254                 areaData := xlsx.MergeCells.Cells[i]
255                 coordinates, err := f.areaRefToCoordinates(areaData.Ref)
256                 if err != nil {
257                         return err
258                 }
259                 x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
260                 if dir == rows {
261                         if y1 == num && y2 == num && offset < 0 {
262                                 f.deleteMergeCell(xlsx, i)
263                                 i--
264                         }
265                         y1 = f.adjustMergeCellsHelper(y1, num, offset)
266                         y2 = f.adjustMergeCellsHelper(y2, num, offset)
267                 } else {
268                         if x1 == num && x2 == num && offset < 0 {
269                                 f.deleteMergeCell(xlsx, i)
270                                 i--
271                         }
272                         x1 = f.adjustMergeCellsHelper(x1, num, offset)
273                         x2 = f.adjustMergeCellsHelper(x2, num, offset)
274                 }
275                 if x1 == x2 && y1 == y2 {
276                         f.deleteMergeCell(xlsx, i)
277                         i--
278                 }
279                 if areaData.Ref, err = f.coordinatesToAreaRef([]int{x1, y1, x2, y2}); err != nil {
280                         return err
281                 }
282         }
283         return nil
284 }
285
286 // adjustMergeCellsHelper provides a function for adjusting merge cells to
287 // compare and calculate cell axis by the given pivot, operation axis and
288 // offset.
289 func (f *File) adjustMergeCellsHelper(pivot, num, offset int) int {
290         if pivot >= num {
291                 pivot += offset
292                 if pivot < 1 {
293                         return 1
294                 }
295                 return pivot
296         }
297         return pivot
298 }
299
300 // deleteMergeCell provides a function to delete merged cell by given index.
301 func (f *File) deleteMergeCell(sheet *xlsxWorksheet, idx int) {
302         if len(sheet.MergeCells.Cells) > idx {
303                 sheet.MergeCells.Cells = append(sheet.MergeCells.Cells[:idx], sheet.MergeCells.Cells[idx+1:]...)
304                 sheet.MergeCells.Count = len(sheet.MergeCells.Cells)
305         }
306 }
307
308 // adjustCalcChain provides a function to update the calculation chain when
309 // inserting or deleting rows or columns.
310 func (f *File) adjustCalcChain(dir adjustDirection, num, offset int) error {
311         if f.CalcChain == nil {
312                 return nil
313         }
314         for index, c := range f.CalcChain.C {
315                 colNum, rowNum, err := CellNameToCoordinates(c.R)
316                 if err != nil {
317                         return err
318                 }
319                 if dir == rows && num <= rowNum {
320                         if newRow := rowNum + offset; newRow > 0 {
321                                 f.CalcChain.C[index].R, _ = CoordinatesToCellName(colNum, newRow)
322                         }
323                 }
324                 if dir == columns && num <= colNum {
325                         if newCol := colNum + offset; newCol > 0 {
326                                 f.CalcChain.C[index].R, _ = CoordinatesToCellName(newCol, rowNum)
327                         }
328                 }
329         }
330         return nil
331 }