adjust.go 9.7 KB
Newer Older
xurime's avatar
xurime 已提交
1
// Copyright 2016 - 2020 The excelize Authors. All rights reserved. Use of
xurime's avatar
xurime 已提交
2 3 4 5 6 7
// 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
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
8
// charts of XLSX. This library needs Go version 1.10 or later.
xurime's avatar
xurime 已提交
9

10 11
package excelize

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

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
//
33
// TODO: adjustPageBreaks, adjustComments, adjustDataValidations, adjustProtectedCells
34
//
35
func (f *File) adjustHelper(sheet string, dir adjustDirection, num, offset int) error {
xurime's avatar
xurime 已提交
36 37 38 39
	xlsx, err := f.workSheetReader(sheet)
	if err != nil {
		return err
	}
40 41 42 43 44 45
	if dir == rows {
		f.adjustRowDimensions(xlsx, num, offset)
	} else {
		f.adjustColDimensions(xlsx, num, offset)
	}
	f.adjustHyperlinks(xlsx, sheet, dir, num, offset)
xurime's avatar
xurime 已提交
46
	if err = f.adjustMergeCells(xlsx, dir, num, offset); err != nil {
47 48
		return err
	}
xurime's avatar
xurime 已提交
49
	if err = f.adjustAutoFilter(xlsx, dir, num, offset); err != nil {
50 51
		return err
	}
52 53 54
	if err = f.adjustCalcChain(dir, num, offset); err != nil {
		return err
	}
55
	checkSheet(xlsx)
56
	_ = checkRow(xlsx)
57 58 59 60 61

	if xlsx.MergeCells != nil && len(xlsx.MergeCells.Cells) == 0 {
		xlsx.MergeCells = nil
	}

62
	return nil
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
}

// adjustColDimensions provides a function to update column dimensions when
// inserting or deleting rows or columns.
func (f *File) adjustColDimensions(xlsx *xlsxWorksheet, col, offset int) {
	for rowIdx := range xlsx.SheetData.Row {
		for colIdx, v := range xlsx.SheetData.Row[rowIdx].C {
			cellCol, cellRow, _ := CellNameToCoordinates(v.R)
			if col <= cellCol {
				if newCol := cellCol + offset; newCol > 0 {
					xlsx.SheetData.Row[rowIdx].C[colIdx].R, _ = CoordinatesToCellName(newCol, cellRow)
				}
			}
		}
	}
}

// adjustRowDimensions provides a function to update row dimensions when
// inserting or deleting rows or columns.
func (f *File) adjustRowDimensions(xlsx *xlsxWorksheet, row, offset int) {
xurime's avatar
xurime 已提交
83 84
	for i := range xlsx.SheetData.Row {
		r := &xlsx.SheetData.Row[i]
85
		if newRow := r.R + offset; r.R >= row && newRow > 0 {
xurime's avatar
xurime 已提交
86
			f.ajustSingleRowDimensions(r, newRow)
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
		}
	}
}

// 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.
func (f *File) adjustHyperlinks(xlsx *xlsxWorksheet, sheet string, dir adjustDirection, num, offset int) {
	// short path
	if xlsx.Hyperlinks == nil || len(xlsx.Hyperlinks.Hyperlink) == 0 {
		return
	}

	// order is important
	if offset < 0 {
		for rowIdx, linkData := range xlsx.Hyperlinks.Hyperlink {
			colNum, rowNum, _ := CellNameToCoordinates(linkData.Ref)

			if (dir == rows && num == rowNum) || (dir == columns && num == colNum) {
				f.deleteSheetRelationships(sheet, linkData.RID)
				if len(xlsx.Hyperlinks.Hyperlink) > 1 {
					xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink[:rowIdx],
						xlsx.Hyperlinks.Hyperlink[rowIdx+1:]...)
				} else {
					xlsx.Hyperlinks = nil
				}
			}
		}
	}

	if xlsx.Hyperlinks == nil {
		return
	}

	for i := range xlsx.Hyperlinks.Hyperlink {
		link := &xlsx.Hyperlinks.Hyperlink[i] // get reference
		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.
147
func (f *File) adjustAutoFilter(xlsx *xlsxWorksheet, dir adjustDirection, num, offset int) error {
148
	if xlsx.AutoFilter == nil {
149
		return nil
150 151
	}

152
	coordinates, err := f.areaRefToCoordinates(xlsx.AutoFilter.Ref)
153
	if err != nil {
154
		return err
155
	}
156
	x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
157

158
	if (dir == rows && y1 == num && offset < 0) || (dir == columns && x1 == num && x2 == num) {
159 160 161
		xlsx.AutoFilter = nil
		for rowIdx := range xlsx.SheetData.Row {
			rowData := &xlsx.SheetData.Row[rowIdx]
162
			if rowData.R > y1 && rowData.R <= y2 {
163 164 165
				rowData.Hidden = false
			}
		}
166
		return nil
167 168
	}

169 170 171 172 173 174 175 176 177 178 179 180 181
	coordinates = f.adjustAutoFilterHelper(dir, coordinates, num, offset)
	x1, y1, x2, y2 = coordinates[0], coordinates[1], coordinates[2], coordinates[3]

	if xlsx.AutoFilter.Ref, err = f.coordinatesToAreaRef([]int{x1, y1, x2, y2}); err != nil {
		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 {
182
	if dir == rows {
183 184
		if coordinates[1] >= num {
			coordinates[1] += offset
185
		}
186 187
		if coordinates[3] >= num {
			coordinates[3] += offset
188 189
		}
	} else {
190 191
		if coordinates[2] >= num {
			coordinates[2] += offset
192 193
		}
	}
194 195
	return coordinates
}
196

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) {
	rng := strings.Split(ref, ":")
C
Cameron Howey 已提交
201 202 203 204 205 206 207
	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)
208 209 210 211 212 213 214 215 216
	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 已提交
217 218
// sortCoordinates provides a function to correct the coordinate area, such
// correct C1:B3 to B1:C3.
C
Cameron Howey 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231
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
}

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
// 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
247 248 249 250
}

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

256 257
	for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
		areaData := xlsx.MergeCells.Cells[i]
258
		coordinates, err := f.areaRefToCoordinates(areaData.Ref)
259
		if err != nil {
260
			return err
261
		}
262
		x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
263
		if dir == rows {
264 265
			if y1 == num && y2 == num && offset < 0 {
				f.deleteMergeCell(xlsx, i)
266
				i--
267 268 269
			}
			y1 = f.adjustMergeCellsHelper(y1, num, offset)
			y2 = f.adjustMergeCellsHelper(y2, num, offset)
270
		} else {
271 272
			if x1 == num && x2 == num && offset < 0 {
				f.deleteMergeCell(xlsx, i)
273
				i--
274
			}
275 276
			x1 = f.adjustMergeCellsHelper(x1, num, offset)
			x2 = f.adjustMergeCellsHelper(x2, num, offset)
277
		}
278 279
		if x1 == x2 && y1 == y2 {
			f.deleteMergeCell(xlsx, i)
280
			i--
281 282
		}
		if areaData.Ref, err = f.coordinatesToAreaRef([]int{x1, y1, x2, y2}); err != nil {
283
			return err
284
		}
285 286 287
	}
	return nil
}
288

289 290 291 292 293 294 295 296
// 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
297
		}
298 299 300 301
		return pivot
	}
	return pivot
}
302

303 304
// deleteMergeCell provides a function to delete merged cell by given index.
func (f *File) deleteMergeCell(sheet *xlsxWorksheet, idx int) {
305
	if len(sheet.MergeCells.Cells) > idx {
306 307
		sheet.MergeCells.Cells = append(sheet.MergeCells.Cells[:idx], sheet.MergeCells.Cells[idx+1:]...)
		sheet.MergeCells.Count = len(sheet.MergeCells.Cells)
308 309
	}
}
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

// adjustCalcChain provides a function to update the calculation chain when
// inserting or deleting rows or columns.
func (f *File) adjustCalcChain(dir adjustDirection, num, offset int) error {
	if f.CalcChain == nil {
		return nil
	}
	for index, c := range f.CalcChain.C {
		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
}