adjust.go 9.9 KB
Newer Older
1
// Copyright 2016 - 2021 The excelize Authors. All rights reserved. Use of
xurime's avatar
xurime 已提交
2 3 4 5
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
xurime's avatar
xurime 已提交
6 7 8 9 10
// and read from XLSX / XLSM / XLTM files. Supports reading and writing
// spreadsheet documents generated by Microsoft Exce™ 2007 and later. Supports
// complex components by high compatibility, and provided streaming API for
// generating or reading data from a worksheet with huge amounts of data. This
// library needs Go version 1.10 or later.
xurime's avatar
xurime 已提交
11

12 13
package excelize

14 15 16 17
import (
	"errors"
	"strings"
)
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

type adjustDirection bool

const (
	columns adjustDirection = false
	rows    adjustDirection = true
)

// adjustHelper provides a function to adjust rows and columns dimensions,
// hyperlinks, merged cells and auto filter when inserting or deleting rows or
// columns.
//
// sheet: Worksheet name that we're editing
// column: Index number of the column we're inserting/deleting before
// row: Index number of the row we're inserting/deleting before
// offset: Number of rows/column to insert/delete negative values indicate deletion
//
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)
xurime's avatar
xurime 已提交
39 40 41
	if err != nil {
		return err
	}
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 49
	f.adjustHyperlinks(ws, sheet, dir, num, offset)
	if err = f.adjustMergeCells(ws, dir, num, offset); err != nil {
50 51
		return err
	}
52
	if err = f.adjustAutoFilter(ws, dir, num, offset); err != nil {
53 54
		return err
	}
55
	if err = f.adjustCalcChain(dir, num, offset, sheetID); err != nil {
56 57
		return err
	}
58 59
	checkSheet(ws)
	_ = checkRow(ws)
60

61 62
	if ws.MergeCells != nil && len(ws.MergeCells.Cells) == 0 {
		ws.MergeCells = nil
63 64
	}

65
	return nil
66 67 68 69
}

// adjustColDimensions provides a function to update column dimensions when
// inserting or deleting rows or columns.
70 71 72
func (f *File) adjustColDimensions(ws *xlsxWorksheet, col, offset int) {
	for rowIdx := range ws.SheetData.Row {
		for colIdx, v := range ws.SheetData.Row[rowIdx].C {
73 74 75
			cellCol, cellRow, _ := CellNameToCoordinates(v.R)
			if col <= cellCol {
				if newCol := cellCol + offset; newCol > 0 {
76
					ws.SheetData.Row[rowIdx].C[colIdx].R, _ = CoordinatesToCellName(newCol, cellRow)
77 78 79 80 81 82 83 84
				}
			}
		}
	}
}

// adjustRowDimensions provides a function to update row dimensions when
// inserting or deleting rows or columns.
85 86 87
func (f *File) adjustRowDimensions(ws *xlsxWorksheet, row, offset int) {
	for i := range ws.SheetData.Row {
		r := &ws.SheetData.Row[i]
88
		if newRow := r.R + offset; r.R >= row && newRow > 0 {
xurime's avatar
xurime 已提交
89
			f.ajustSingleRowDimensions(r, newRow)
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
		}
	}
}

// ajustSingleRowDimensions provides a function to ajust single row dimensions.
func (f *File) ajustSingleRowDimensions(r *xlsxRow, num int) {
	r.R = num
	for i, col := range r.C {
		colName, _, _ := SplitCellName(col.R)
		r.C[i].R, _ = JoinCellName(colName, num)
	}
}

// adjustHyperlinks provides a function to update hyperlinks when inserting or
// 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 109 110 111 112
		return
	}

	// order is important
	if offset < 0 {
113 114
		for i := len(ws.Hyperlinks.Hyperlink) - 1; i >= 0; i-- {
			linkData := ws.Hyperlinks.Hyperlink[i]
115 116 117 118
			colNum, rowNum, _ := CellNameToCoordinates(linkData.Ref)

			if (dir == rows && num == rowNum) || (dir == columns && num == colNum) {
				f.deleteSheetRelationships(sheet, linkData.RID)
119 120 121
				if len(ws.Hyperlinks.Hyperlink) > 1 {
					ws.Hyperlinks.Hyperlink = append(ws.Hyperlinks.Hyperlink[:i],
						ws.Hyperlinks.Hyperlink[i+1:]...)
122
				} else {
123
					ws.Hyperlinks = nil
124 125 126 127
				}
			}
		}
	}
128
	if ws.Hyperlinks == nil {
129 130
		return
	}
131 132
	for i := range ws.Hyperlinks.Hyperlink {
		link := &ws.Hyperlinks.Hyperlink[i] // get reference
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
		colNum, rowNum, _ := CellNameToCoordinates(link.Ref)
		if dir == rows {
			if rowNum >= num {
				link.Ref, _ = CoordinatesToCellName(colNum, rowNum+offset)
			}
		} else {
			if colNum >= num {
				link.Ref, _ = CoordinatesToCellName(colNum+offset, rowNum)
			}
		}
	}
}

// adjustAutoFilter provides a function to update the auto filter when
// inserting or deleting rows or columns.
148 149
func (f *File) adjustAutoFilter(ws *xlsxWorksheet, dir adjustDirection, num, offset int) error {
	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 161 162
		ws.AutoFilter = nil
		for rowIdx := range ws.SheetData.Row {
			rowData := &ws.SheetData.Row[rowIdx]
163
			if rowData.R > y1 && rowData.R <= y2 {
164 165 166
				rowData.Hidden = false
			}
		}
167
		return nil
168 169
	}

170 171 172
	coordinates = f.adjustAutoFilterHelper(dir, coordinates, num, offset)
	x1, y1, x2, y2 = coordinates[0], coordinates[1], coordinates[2], coordinates[3]

173
	if ws.AutoFilter.Ref, err = f.coordinatesToAreaRef([]int{x1, y1, x2, y2}); err != nil {
174 175 176 177 178 179 180 181 182
		return err
	}
	return nil
}

// adjustAutoFilterHelper provides a function for adjusting auto filter to
// compare and calculate cell axis by the given adjust direction, operation
// axis and offset.
func (f *File) adjustAutoFilterHelper(dir adjustDirection, coordinates []int, num, offset int) []int {
183
	if dir == rows {
184 185
		if coordinates[1] >= num {
			coordinates[1] += offset
186
		}
187 188
		if coordinates[3] >= num {
			coordinates[3] += offset
189 190
		}
	} else {
191 192
		if coordinates[2] >= num {
			coordinates[2] += offset
193 194
		}
	}
195 196
	return coordinates
}
197

198 199 200
// areaRefToCoordinates provides a function to convert area reference to a
// pair of coordinates.
func (f *File) areaRefToCoordinates(ref string) ([]int, error) {
201
	rng := strings.Split(strings.Replace(ref, "$", "", -1), ":")
C
Cameron Howey 已提交
202 203 204 205 206 207 208
	return areaRangeToCoordinates(rng[0], rng[1])
}

// areaRangeToCoordinates provides a function to convert cell range to a
// pair of coordinates.
func areaRangeToCoordinates(firstCell, lastCell string) ([]int, error) {
	coordinates := make([]int, 4)
209 210 211 212 213 214 215 216 217
	var err error
	coordinates[0], coordinates[1], err = CellNameToCoordinates(firstCell)
	if err != nil {
		return coordinates, err
	}
	coordinates[2], coordinates[3], err = CellNameToCoordinates(lastCell)
	return coordinates, err
}

xurime's avatar
xurime 已提交
218 219
// sortCoordinates provides a function to correct the coordinate area, such
// correct C1:B3 to B1:C3.
C
Cameron Howey 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232
func sortCoordinates(coordinates []int) error {
	if len(coordinates) != 4 {
		return errors.New("coordinates length must be 4")
	}
	if coordinates[2] < coordinates[0] {
		coordinates[2], coordinates[0] = coordinates[0], coordinates[2]
	}
	if coordinates[3] < coordinates[1] {
		coordinates[3], coordinates[1] = coordinates[1], coordinates[3]
	}
	return nil
}

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
// coordinatesToAreaRef provides a function to convert a pair of coordinates
// to area reference.
func (f *File) coordinatesToAreaRef(coordinates []int) (string, error) {
	if len(coordinates) != 4 {
		return "", errors.New("coordinates length must be 4")
	}
	firstCell, err := CoordinatesToCellName(coordinates[0], coordinates[1])
	if err != nil {
		return "", err
	}
	lastCell, err := CoordinatesToCellName(coordinates[2], coordinates[3])
	if err != nil {
		return "", err
	}
	return firstCell + ":" + lastCell, err
248 249 250 251
}

// adjustMergeCells provides a function to update merged cells when inserting
// or deleting rows or columns.
252 253
func (f *File) adjustMergeCells(ws *xlsxWorksheet, dir adjustDirection, num, offset int) error {
	if ws.MergeCells == nil {
254
		return nil
255 256
	}

257 258
	for i := 0; i < len(ws.MergeCells.Cells); i++ {
		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 270
			}
			y1 = f.adjustMergeCellsHelper(y1, num, offset)
			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 277
			x1 = f.adjustMergeCellsHelper(x1, num, offset)
			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 288
	}
	return nil
}
289

290 291 292 293 294 295 296 297
// adjustMergeCellsHelper provides a function for adjusting merge cells to
// compare and calculate cell axis by the given pivot, operation axis and
// offset.
func (f *File) adjustMergeCellsHelper(pivot, num, offset int) int {
	if pivot >= num {
		pivot += offset
		if pivot < 1 {
			return 1
298
		}
299 300 301 302
		return pivot
	}
	return pivot
}
303

304
// deleteMergeCell provides a function to delete merged cell by given index.
305 306 307 308
func (f *File) deleteMergeCell(ws *xlsxWorksheet, idx int) {
	if len(ws.MergeCells.Cells) > idx {
		ws.MergeCells.Cells = append(ws.MergeCells.Cells[:idx], ws.MergeCells.Cells[idx+1:]...)
		ws.MergeCells.Count = len(ws.MergeCells.Cells)
309 310
	}
}
311 312 313

// adjustCalcChain provides a function to update the calculation chain when
// inserting or deleting rows or columns.
314
func (f *File) adjustCalcChain(dir adjustDirection, num, offset, sheetID int) error {
315 316 317 318
	if f.CalcChain == nil {
		return nil
	}
	for index, c := range f.CalcChain.C {
319 320 321
		if c.I != sheetID {
			continue
		}
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
		colNum, rowNum, err := CellNameToCoordinates(c.R)
		if err != nil {
			return err
		}
		if dir == rows && num <= rowNum {
			if newRow := rowNum + offset; newRow > 0 {
				f.CalcChain.C[index].R, _ = CoordinatesToCellName(colNum, newRow)
			}
		}
		if dir == columns && num <= colNum {
			if newCol := colNum + offset; newCol > 0 {
				f.CalcChain.C[index].R, _ = CoordinatesToCellName(newCol, rowNum)
			}
		}
	}
	return nil
}