col.go 22.2 KB
Newer Older
1
// Copyright 2016 - 2024 The excelize Authors. All rights reserved. Use of
xurime's avatar
xurime 已提交
2 3 4
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
5 6 7 8 9
// Package excelize providing a set of functions that allow you to write to and
// read from XLAM / XLSM / XLSX / XLTM / XLTX files. Supports reading and
// writing spreadsheet documents generated by Microsoft Excel™ 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
10
// data. This library needs Go version 1.18 or later.
xurime's avatar
xurime 已提交
11

12 13
package excelize

14
import (
J
Jérôme Pogeant 已提交
15 16
	"bytes"
	"encoding/xml"
17
	"math"
18
	"strconv"
19
	"strings"
20 21

	"github.com/mohae/deepcopy"
22
)
23

24 25
// Define the default cell size and EMU unit of measurement.
const (
26
	defaultColWidth        float64 = 9.140625
27
	defaultColWidthPixels  float64 = 64
28
	defaultRowHeight       float64 = 15
29 30
	defaultRowHeightPixels float64 = 20
	EMU                    int     = 9525
31 32
)

J
Jérôme Pogeant 已提交
33 34
// Cols defines an iterator to a sheet
type Cols struct {
35 36 37 38 39 40
	err                                    error
	curCol, totalCols, totalRows, stashCol int
	rawCellValue                           bool
	sheet                                  string
	f                                      *File
	sheetXML                               []byte
41
	sst                                    *xlsxSST
42 43
}

44 45 46 47 48 49 50 51 52
// GetCols gets the value of all cells by columns on the worksheet based on the
// given worksheet name, returned as a two-dimensional array, where the value
// of the cell is converted to the `string` type. If the cell format can be
// applied to the value of the cell, the applied value will be used, otherwise
// the original value will be used.
//
// For example, get and traverse the value of all cells by columns on a
// worksheet named
// 'Sheet1':
J
Jérôme Pogeant 已提交
53
//
54 55 56 57 58 59 60 61 62 63 64
//	cols, err := f.GetCols("Sheet1")
//	if err != nil {
//	    fmt.Println(err)
//	    return
//	}
//	for _, col := range cols {
//	    for _, rowCell := range col {
//	        fmt.Print(rowCell, "\t")
//	    }
//	    fmt.Println()
//	}
xurime's avatar
xurime 已提交
65
func (f *File) GetCols(sheet string, opts ...Options) ([][]string, error) {
66
	if _, err := f.workSheetReader(sheet); err != nil {
J
Jérôme Pogeant 已提交
67 68
		return nil, err
	}
69
	cols, err := f.Cols(sheet)
J
Jérôme Pogeant 已提交
70 71
	results := make([][]string, 0, 64)
	for cols.Next() {
xurime's avatar
xurime 已提交
72
		col, _ := cols.Rows(opts...)
J
Jérôme Pogeant 已提交
73 74
		results = append(results, col)
	}
75
	return results, err
J
Jérôme Pogeant 已提交
76 77
}

78
// Next will return true if the next column is found.
J
Jérôme Pogeant 已提交
79 80
func (cols *Cols) Next() bool {
	cols.curCol++
81
	return cols.curCol <= cols.totalCols
J
Jérôme Pogeant 已提交
82 83
}

84
// Error will return an error when the error occurs.
J
Jérôme Pogeant 已提交
85 86 87 88
func (cols *Cols) Error() error {
	return cols.err
}

89
// Rows return the current column's row values.
xurime's avatar
xurime 已提交
90
func (cols *Cols) Rows(opts ...Options) ([]string, error) {
91
	var rowIterator rowXMLIterator
J
Jérôme Pogeant 已提交
92
	if cols.stashCol >= cols.curCol {
93
		return rowIterator.cells, rowIterator.err
J
Jérôme Pogeant 已提交
94
	}
95
	cols.rawCellValue = cols.f.getOptions(opts...).RawCellValue
96 97 98
	if cols.sst, rowIterator.err = cols.f.sharedStringsReader(); rowIterator.err != nil {
		return rowIterator.cells, rowIterator.err
	}
99 100 101 102 103 104
	decoder := cols.f.xmlNewDecoder(bytes.NewReader(cols.sheetXML))
	for {
		token, _ := decoder.Token()
		if token == nil {
			break
		}
105
		switch xmlElement := token.(type) {
106
		case xml.StartElement:
107 108 109 110
			rowIterator.inElement = xmlElement.Name.Local
			if rowIterator.inElement == "row" {
				rowIterator.cellCol = 0
				rowIterator.cellRow++
111
				attrR, _ := attrValToInt("r", xmlElement.Attr)
112
				if attrR != 0 {
113
					rowIterator.cellRow = attrR
114 115
				}
			}
116 117
			if cols.rowXMLHandler(&rowIterator, &xmlElement, decoder); rowIterator.err != nil {
				return rowIterator.cells, rowIterator.err
118
			}
119 120
		case xml.EndElement:
			if xmlElement.Name.Local == "sheetData" {
121
				return rowIterator.cells, rowIterator.err
122
			}
123
		}
J
Jérôme Pogeant 已提交
124
	}
125
	return rowIterator.cells, rowIterator.err
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
}

// columnXMLIterator defined runtime use field for the worksheet column SAX parser.
type columnXMLIterator struct {
	err                  error
	cols                 Cols
	cellCol, curRow, row int
}

// columnXMLHandler parse the column XML element of the worksheet.
func columnXMLHandler(colIterator *columnXMLIterator, xmlElement *xml.StartElement) {
	colIterator.err = nil
	inElement := xmlElement.Name.Local
	if inElement == "row" {
		colIterator.row++
		for _, attr := range xmlElement.Attr {
			if attr.Name.Local == "r" {
				if colIterator.curRow, colIterator.err = strconv.Atoi(attr.Value); colIterator.err != nil {
					return
				}
				colIterator.row = colIterator.curRow
			}
		}
149
		colIterator.cols.totalRows = colIterator.row
150 151 152 153 154 155 156 157 158 159 160
		colIterator.cellCol = 0
	}
	if inElement == "c" {
		colIterator.cellCol++
		for _, attr := range xmlElement.Attr {
			if attr.Name.Local == "r" {
				if colIterator.cellCol, _, colIterator.err = CellNameToCoordinates(attr.Value); colIterator.err != nil {
					return
				}
			}
		}
161 162
		if colIterator.cellCol > colIterator.cols.totalCols {
			colIterator.cols.totalCols = colIterator.cellCol
163 164
		}
	}
J
Jérôme Pogeant 已提交
165 166
}

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
// rowXMLHandler parse the row XML element of the worksheet.
func (cols *Cols) rowXMLHandler(rowIterator *rowXMLIterator, xmlElement *xml.StartElement, decoder *xml.Decoder) {
	if rowIterator.inElement == "c" {
		rowIterator.cellCol++
		for _, attr := range xmlElement.Attr {
			if attr.Name.Local == "r" {
				if rowIterator.cellCol, rowIterator.cellRow, rowIterator.err = CellNameToCoordinates(attr.Value); rowIterator.err != nil {
					return
				}
			}
		}
		blank := rowIterator.cellRow - len(rowIterator.cells)
		for i := 1; i < blank; i++ {
			rowIterator.cells = append(rowIterator.cells, "")
		}
		if rowIterator.cellCol == cols.curCol {
			colCell := xlsxC{}
			_ = decoder.DecodeElement(&colCell, xmlElement)
			val, _ := colCell.getValueFrom(cols.f, cols.sst, cols.rawCellValue)
			rowIterator.cells = append(rowIterator.cells, val)
		}
	}
}

191
// Cols returns a columns iterator, used for streaming reading data for a
192 193
// worksheet with a large data. This function is concurrency safe. For
// example:
J
Jérôme Pogeant 已提交
194
//
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
//	cols, err := f.Cols("Sheet1")
//	if err != nil {
//	    fmt.Println(err)
//	    return
//	}
//	for cols.Next() {
//	    col, err := cols.Rows()
//	    if err != nil {
//	        fmt.Println(err)
//	    }
//	    for _, rowCell := range col {
//	        fmt.Print(rowCell, "\t")
//	    }
//	    fmt.Println()
//	}
J
Jérôme Pogeant 已提交
210
func (f *File) Cols(sheet string) (*Cols, error) {
211 212 213
	if err := checkSheetName(sheet); err != nil {
		return nil, err
	}
214
	name, ok := f.getSheetXMLPath(sheet)
J
Jérôme Pogeant 已提交
215 216 217
	if !ok {
		return nil, ErrSheetNotExist{sheet}
	}
218 219 220 221 222
	if worksheet, ok := f.Sheet.Load(name); ok && worksheet != nil {
		ws := worksheet.(*xlsxWorksheet)
		ws.mu.Lock()
		defer ws.mu.Unlock()
		output, _ := xml.Marshal(ws)
223
		f.saveFileList(name, f.replaceNameSpaceBytes(name, output))
J
Jérôme Pogeant 已提交
224
	}
225
	var colIterator columnXMLIterator
226
	colIterator.cols.sheetXML = f.readBytes(name)
227
	decoder := f.xmlNewDecoder(bytes.NewReader(colIterator.cols.sheetXML))
J
Jérôme Pogeant 已提交
228 229 230 231 232
	for {
		token, _ := decoder.Token()
		if token == nil {
			break
		}
233
		switch xmlElement := token.(type) {
J
Jérôme Pogeant 已提交
234
		case xml.StartElement:
235 236 237
			columnXMLHandler(&colIterator, &xmlElement)
			if colIterator.err != nil {
				return &colIterator.cols, colIterator.err
238
			}
239 240 241
		case xml.EndElement:
			if xmlElement.Name.Local == "sheetData" {
				colIterator.cols.f = f
242
				colIterator.cols.sheet = sheet
243
				return &colIterator.cols, nil
J
Jérôme Pogeant 已提交
244 245 246
			}
		}
	}
247
	return &colIterator.cols, nil
J
Jérôme Pogeant 已提交
248 249
}

250
// GetColVisible provides a function to get visible of a single column by given
251 252
// worksheet name and column name. This function is concurrency safe. For
// example, get visible state of column D in Sheet1:
253
//
254
//	visible, err := f.GetColVisible("Sheet1", "D")
255 256 257
func (f *File) GetColVisible(sheet, col string) (bool, error) {
	colNum, err := ColumnNameToNumber(col)
	if err != nil {
258
		return true, err
259
	}
xurime's avatar
xurime 已提交
260
	f.mu.Lock()
261
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
262
	if err != nil {
xurime's avatar
xurime 已提交
263
		f.mu.Unlock()
xurime's avatar
xurime 已提交
264 265
		return false, err
	}
xurime's avatar
xurime 已提交
266
	f.mu.Unlock()
267 268
	ws.mu.Lock()
	defer ws.mu.Unlock()
269
	if ws.Cols == nil {
270
		return true, err
271
	}
272
	visible := true
273 274
	for c := range ws.Cols.Col {
		colData := &ws.Cols.Col[c]
275 276
		if colData.Min <= colNum && colNum <= colData.Max {
			visible = !colData.Hidden
277 278
		}
	}
279
	return visible, err
280 281
}

282
// SetColVisible provides a function to set visible columns by given worksheet
283
// name, columns range and visibility. This function is concurrency safe.
284 285
//
// For example hide column D on Sheet1:
286
//
287
//	err := f.SetColVisible("Sheet1", "D", false)
288
//
289
// Hide the columns from D to F (included):
290
//
291
//	err := f.SetColVisible("Sheet1", "D:F", false)
292
func (f *File) SetColVisible(sheet, columns string, visible bool) error {
293
	minVal, maxVal, err := f.parseColRange(columns)
294 295 296
	if err != nil {
		return err
	}
297
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
298 299 300
	if err != nil {
		return err
	}
301 302
	ws.mu.Lock()
	defer ws.mu.Unlock()
303
	colData := xlsxCol{
304 305
		Min:         minVal,
		Max:         maxVal,
306
		Width:       float64Ptr(defaultColWidth),
307
		Hidden:      !visible,
308 309
		CustomWidth: true,
	}
310
	if ws.Cols == nil {
311
		cols := xlsxCols{}
312
		cols.Col = append(cols.Col, colData)
313
		ws.Cols = &cols
314 315
		return nil
	}
316
	ws.Cols.Col = flatCols(colData, ws.Cols.Col, func(fc, c xlsxCol) xlsxCol {
317 318 319 320 321 322 323 324 325
		fc.BestFit = c.BestFit
		fc.Collapsed = c.Collapsed
		fc.CustomWidth = c.CustomWidth
		fc.OutlineLevel = c.OutlineLevel
		fc.Phonetic = c.Phonetic
		fc.Style = c.Style
		fc.Width = c.Width
		return fc
	})
326
	return nil
327 328
}

329 330 331
// GetColOutlineLevel provides a function to get outline level of a single
// column by given worksheet name and column name. For example, get outline
// level of column D in Sheet1:
332
//
333
//	level, err := f.GetColOutlineLevel("Sheet1", "D")
334
func (f *File) GetColOutlineLevel(sheet, col string) (uint8, error) {
335
	level := uint8(0)
336 337 338 339
	colNum, err := ColumnNameToNumber(col)
	if err != nil {
		return level, err
	}
340
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
341 342 343
	if err != nil {
		return 0, err
	}
344
	if ws.Cols == nil {
345
		return level, err
346
	}
347 348
	for c := range ws.Cols.Col {
		colData := &ws.Cols.Col[c]
349
		if colData.Min <= colNum && colNum <= colData.Max {
xurime's avatar
xurime 已提交
350
			level = colData.OutlineLevel
351 352
		}
	}
353
	return level, err
354 355
}

356
// parseColRange parse and convert column range with column name to the column number.
357
func (f *File) parseColRange(columns string) (min, max int, err error) {
358
	colsTab := strings.Split(columns, ":")
359
	min, err = ColumnNameToNumber(colsTab[0])
360 361 362
	if err != nil {
		return
	}
363
	max = min
364
	if len(colsTab) == 2 {
365
		if max, err = ColumnNameToNumber(colsTab[1]); err != nil {
366 367 368
			return
		}
	}
369 370
	if max < min {
		min, max = max, min
371 372 373 374
	}
	return
}

375
// SetColOutlineLevel provides a function to set outline level of a single
xurime's avatar
xurime 已提交
376 377
// column by given worksheet name and column name. The value of parameter
// 'level' is 1-7. For example, set outline level of column D in Sheet1 to 2:
378
//
379
//	err := f.SetColOutlineLevel("Sheet1", "D", 2)
380
func (f *File) SetColOutlineLevel(sheet, col string, level uint8) error {
xurime's avatar
xurime 已提交
381
	if level > 7 || level < 1 {
382
		return ErrOutlineLevel
xurime's avatar
xurime 已提交
383
	}
384 385 386 387
	colNum, err := ColumnNameToNumber(col)
	if err != nil {
		return err
	}
388 389 390
	colData := xlsxCol{
		Min:          colNum,
		Max:          colNum,
391 392 393
		OutlineLevel: level,
		CustomWidth:  true,
	}
394
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
395 396 397
	if err != nil {
		return err
	}
398
	if ws.Cols == nil {
399
		cols := xlsxCols{}
400
		cols.Col = append(cols.Col, colData)
401
		ws.Cols = &cols
402
		return err
403
	}
404
	ws.Cols.Col = flatCols(colData, ws.Cols.Col, func(fc, c xlsxCol) xlsxCol {
405 406 407 408 409 410 411 412 413
		fc.BestFit = c.BestFit
		fc.Collapsed = c.Collapsed
		fc.CustomWidth = c.CustomWidth
		fc.Hidden = c.Hidden
		fc.Phonetic = c.Phonetic
		fc.Style = c.Style
		fc.Width = c.Width
		return fc
	})
414
	return err
415 416
}

417
// SetColStyle provides a function to set style of columns by given worksheet
418 419 420
// name, columns range and style ID. This function is concurrency safe. Note
// that this will overwrite the existing styles for the columns, it won't
// append or merge style with existing styles.
421 422 423
//
// For example set style of column H on Sheet1:
//
424
//	err = f.SetColStyle("Sheet1", "H", style)
425 426 427
//
// Set style of columns C:F on Sheet1:
//
428
//	err = f.SetColStyle("Sheet1", "C:F", style)
429
func (f *File) SetColStyle(sheet, columns string, styleID int) error {
430
	minVal, maxVal, err := f.parseColRange(columns)
431 432 433
	if err != nil {
		return err
	}
xurime's avatar
xurime 已提交
434
	f.mu.Lock()
435 436
	s, err := f.stylesReader()
	if err != nil {
xurime's avatar
xurime 已提交
437
		f.mu.Unlock()
438 439
		return err
	}
xurime's avatar
xurime 已提交
440 441 442 443 444 445
	ws, err := f.workSheetReader(sheet)
	if err != nil {
		f.mu.Unlock()
		return err
	}
	f.mu.Unlock()
446
	s.mu.Lock()
447
	if styleID < 0 || s.CellXfs == nil || len(s.CellXfs.Xf) <= styleID {
448
		s.mu.Unlock()
449 450
		return newInvalidStyleID(styleID)
	}
451 452
	s.mu.Unlock()
	ws.mu.Lock()
453 454
	if ws.Cols == nil {
		ws.Cols = &xlsxCols{}
455
	}
456 457 458 459
	width := defaultColWidth
	if ws.SheetFormatPr != nil && ws.SheetFormatPr.DefaultColWidth > 0 {
		width = ws.SheetFormatPr.DefaultColWidth
	}
460
	ws.Cols.Col = flatCols(xlsxCol{
461 462 463
		Min:   minVal,
		Max:   maxVal,
		Width: float64Ptr(width),
464
		Style: styleID,
465
	}, ws.Cols.Col, func(fc, c xlsxCol) xlsxCol {
466 467 468 469 470 471 472 473 474
		fc.BestFit = c.BestFit
		fc.Collapsed = c.Collapsed
		fc.CustomWidth = c.CustomWidth
		fc.Hidden = c.Hidden
		fc.OutlineLevel = c.OutlineLevel
		fc.Phonetic = c.Phonetic
		fc.Width = c.Width
		return fc
	})
475
	ws.mu.Unlock()
476
	if rows := len(ws.SheetData.Row); rows > 0 {
477
		for col := minVal; col <= maxVal; col++ {
478 479
			from, _ := CoordinatesToCellName(col, 1)
			to, _ := CoordinatesToCellName(col, rows)
480
			err = f.SetCellStyle(sheet, from, to, styleID)
481 482
		}
	}
483
	return err
484 485
}

xurime's avatar
xurime 已提交
486
// SetColWidth provides a function to set the width of a single column or
487
// multiple columns. This function is concurrency safe. For example:
488
//
489
//	err := f.SetColWidth("Sheet1", "A", "H", 20)
490
func (f *File) SetColWidth(sheet, startCol, endCol string, width float64) error {
491
	minVal, maxVal, err := f.parseColRange(startCol + ":" + endCol)
492 493 494
	if err != nil {
		return err
	}
495
	if width > MaxColumnWidth {
496
		return ErrColumnWidth
497
	}
xurime's avatar
xurime 已提交
498
	f.mu.Lock()
499
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
500
	if err != nil {
xurime's avatar
xurime 已提交
501
		f.mu.Unlock()
xurime's avatar
xurime 已提交
502 503
		return err
	}
xurime's avatar
xurime 已提交
504
	f.mu.Unlock()
505 506
	ws.mu.Lock()
	defer ws.mu.Unlock()
507
	col := xlsxCol{
508 509
		Min:         minVal,
		Max:         maxVal,
510
		Width:       float64Ptr(width),
511 512
		CustomWidth: true,
	}
513
	if ws.Cols == nil {
514 515
		cols := xlsxCols{}
		cols.Col = append(cols.Col, col)
516
		ws.Cols = &cols
517
		return err
518
	}
519
	ws.Cols.Col = flatCols(col, ws.Cols.Col, func(fc, c xlsxCol) xlsxCol {
520 521 522 523 524 525 526 527
		fc.BestFit = c.BestFit
		fc.Collapsed = c.Collapsed
		fc.Hidden = c.Hidden
		fc.OutlineLevel = c.OutlineLevel
		fc.Phonetic = c.Phonetic
		fc.Style = c.Style
		return fc
	})
528
	return err
529
}
530

531 532 533
// flatCols provides a method for the column's operation functions to flatten
// and check the worksheet columns.
func flatCols(col xlsxCol, cols []xlsxCol, replacer func(fc, c xlsxCol) xlsxCol) []xlsxCol {
534
	var fc []xlsxCol
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
	for i := col.Min; i <= col.Max; i++ {
		c := deepcopy.Copy(col).(xlsxCol)
		c.Min, c.Max = i, i
		fc = append(fc, c)
	}
	inFlat := func(colID int, cols []xlsxCol) (int, bool) {
		for idx, c := range cols {
			if c.Max == colID && c.Min == colID {
				return idx, true
			}
		}
		return -1, false
	}
	for _, column := range cols {
		for i := column.Min; i <= column.Max; i++ {
			if idx, ok := inFlat(i, fc); ok {
				fc[idx] = replacer(fc[idx], column)
				continue
			}
			c := deepcopy.Copy(column).(xlsxCol)
			c.Min, c.Max = i, i
			fc = append(fc, c)
		}
	}
	return fc
}

562 563 564
// positionObjectPixels calculate the vertices that define the position of a
// graphical object within the worksheet in pixels.
//
565 566 567 568 569 570 571 572 573 574 575 576 577
//	      +------------+------------+
//	      |     A      |      B     |
//	+-----+------------+------------+
//	|     |(x1,y1)     |            |
//	|  1  |(A1)._______|______      |
//	|     |    |              |     |
//	|     |    |              |     |
//	+-----+----|    OBJECT    |-----+
//	|     |    |              |     |
//	|  2  |    |______________.     |
//	|     |            |        (B2)|
//	|     |            |     (x2,y2)|
//	+-----+------------+------------+
578
//
xurime's avatar
xurime 已提交
579
// Example of an object that covers some range reference from cell A1 to B2.
580 581 582
//
// Based on the width and height of the object we need to calculate 8 vars:
//
583
//	colStart, rowStart, colEnd, rowEnd, x1, y1, x2, y2.
584 585 586 587 588 589 590 591 592 593 594 595
//
// We also calculate the absolute x and y position of the top left vertex of
// the object. This is required for images.
//
// The width and height of the cells that the object occupies can be
// variable and have to be taken into account.
//
// The values of col_start and row_start are passed in from the calling
// function. The values of col_end and row_end are calculated by
// subtracting the width and height of the object from the width and
// height of the underlying cells.
//
596 597
//	colStart        # Col containing upper left corner of object.
//	x1              # Distance to left side of object.
598
//
599 600
//	rowStart        # Row containing top left corner of object.
//	y1              # Distance to top of object.
601
//
602 603
//	colEnd          # Col containing lower right corner of object.
//	x2              # Distance to right side of object.
604
//
605 606
//	rowEnd          # Row containing bottom right corner of object.
//	y2              # Distance to bottom of object.
607
//
608 609
//	width           # Width of object frame.
//	height          # Height of object frame.
610
func (f *File) positionObjectPixels(sheet string, col, row, x1, y1, width, height int) (int, int, int, int, int, int) {
611
	colIdx, rowIdx := col-1, row-1
612
	// Adjust start column for offsets that are greater than the col width.
613 614 615
	for x1 >= f.getColWidth(sheet, colIdx+1) {
		colIdx++
		x1 -= f.getColWidth(sheet, colIdx)
616 617 618
	}

	// Adjust start row for offsets that are greater than the row height.
619 620 621
	for y1 >= f.getRowHeight(sheet, rowIdx+1) {
		rowIdx++
		y1 -= f.getRowHeight(sheet, rowIdx)
622 623
	}

624
	// Initialized end cell to the same as the start cell.
625
	colEnd, rowEnd := colIdx, rowIdx
626 627 628 629 630

	width += x1
	height += y1

	// Subtract the underlying cell widths to find end cell of the object.
N
nabeyama yoshihide 已提交
631
	for width >= f.getColWidth(sheet, colEnd+1) {
632
		colEnd++
633
		width -= f.getColWidth(sheet, colEnd)
634 635 636
	}

	// Subtract the underlying cell heights to find end cell of the object.
637
	for height >= f.getRowHeight(sheet, rowEnd+1) {
638
		rowEnd++
639
		height -= f.getRowHeight(sheet, rowEnd)
640 641 642
	}

	// The end vertices are whatever is left from the width and height.
643
	return colIdx, rowIdx, colEnd, rowEnd, width, height
644 645
}

xurime's avatar
xurime 已提交
646
// getColWidth provides a function to get column width in pixels by given
647
// sheet name and column number.
648
func (f *File) getColWidth(sheet string, col int) int {
T
three 已提交
649
	ws, _ := f.workSheetReader(sheet)
650 651
	ws.mu.Lock()
	defer ws.mu.Unlock()
T
three 已提交
652
	if ws.Cols != nil {
653
		var width float64
T
three 已提交
654
		for _, v := range ws.Cols.Col {
655 656
			if v.Min <= col && col <= v.Max && v.Width != nil {
				width = *v.Width
657 658 659 660 661 662
			}
		}
		if width != 0 {
			return int(convertColWidthToPixels(width))
		}
	}
663 664 665
	if ws.SheetFormatPr != nil && ws.SheetFormatPr.DefaultColWidth > 0 {
		return int(convertColWidthToPixels(ws.SheetFormatPr.DefaultColWidth))
	}
666
	// Optimization for when the column widths haven't changed.
667
	return int(defaultColWidthPixels)
668 669
}

670
// GetColStyle provides a function to get column style ID by given worksheet
671
// name and column name. This function is concurrency safe.
672 673 674 675 676 677
func (f *File) GetColStyle(sheet, col string) (int, error) {
	var styleID int
	colNum, err := ColumnNameToNumber(col)
	if err != nil {
		return styleID, err
	}
xurime's avatar
xurime 已提交
678
	f.mu.Lock()
679 680
	ws, err := f.workSheetReader(sheet)
	if err != nil {
xurime's avatar
xurime 已提交
681
		f.mu.Unlock()
682 683
		return styleID, err
	}
xurime's avatar
xurime 已提交
684
	f.mu.Unlock()
685 686
	ws.mu.Lock()
	defer ws.mu.Unlock()
687 688 689 690 691 692 693 694 695 696
	if ws.Cols != nil {
		for _, v := range ws.Cols.Col {
			if v.Min <= colNum && colNum <= v.Max {
				styleID = v.Style
			}
		}
	}
	return styleID, err
}

xurime's avatar
xurime 已提交
697
// GetColWidth provides a function to get column width by given worksheet name
698
// and column name. This function is concurrency safe.
699 700 701
func (f *File) GetColWidth(sheet, col string) (float64, error) {
	colNum, err := ColumnNameToNumber(col)
	if err != nil {
702
		return defaultColWidth, err
703
	}
xurime's avatar
xurime 已提交
704
	f.mu.Lock()
705
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
706
	if err != nil {
xurime's avatar
xurime 已提交
707
		f.mu.Unlock()
708
		return defaultColWidth, err
xurime's avatar
xurime 已提交
709
	}
xurime's avatar
xurime 已提交
710
	f.mu.Unlock()
711 712
	ws.mu.Lock()
	defer ws.mu.Unlock()
713
	if ws.Cols != nil {
714
		var width float64
715
		for _, v := range ws.Cols.Col {
716 717
			if v.Min <= colNum && colNum <= v.Max && v.Width != nil {
				width = *v.Width
718 719 720
			}
		}
		if width != 0 {
721
			return width, err
722 723
		}
	}
724 725 726
	if ws.SheetFormatPr != nil && ws.SheetFormatPr.DefaultColWidth > 0 {
		return ws.SheetFormatPr.DefaultColWidth, err
	}
727
	// Optimization for when the column widths haven't changed.
728
	return defaultColWidth, err
729 730
}

731 732 733
// InsertCols provides a function to insert new columns before the given column
// name and number of columns. For example, create two columns before column
// C in Sheet1:
734
//
735 736 737 738 739 740 741
//	err := f.InsertCols("Sheet1", "C", 2)
//
// Use this method with caution, which will affect changes in references such
// as formulas, charts, and so on. If there is any referenced value of the
// worksheet, it will cause a file error when you open it. The excelize only
// partially updates these references currently.
func (f *File) InsertCols(sheet, col string, n int) error {
742 743
	num, err := ColumnNameToNumber(col)
	if err != nil {
744
		return err
745
	}
746 747 748 749
	if n < 1 || n > MaxColumns {
		return ErrColumnNumber
	}
	return f.adjustHelper(sheet, columns, num, n)
750 751
}

xurime's avatar
xurime 已提交
752 753
// RemoveCol provides a function to remove single column by given worksheet
// name and column index. For example, remove column C in Sheet1:
754
//
755
//	err := f.RemoveCol("Sheet1", "C")
756
//
757 758 759 760
// Use this method with caution, which will affect changes in references such
// as formulas, charts, and so on. If there is any referenced value of the
// worksheet, it will cause a file error when you open it. The excelize only
// partially updates these references currently.
761
func (f *File) RemoveCol(sheet, col string) error {
762 763
	num, err := ColumnNameToNumber(col)
	if err != nil {
764
		return err
765 766
	}

767
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
768 769 770
	if err != nil {
		return err
	}
771 772
	for rowIdx := range ws.SheetData.Row {
		rowData := &ws.SheetData.Row[rowIdx]
773 774
		for colIdx := range rowData.C {
			colName, _, _ := SplitCellName(rowData.C[colIdx].R)
775
			if colName == col {
776 777
				rowData.C = append(rowData.C[:colIdx], rowData.C[colIdx+1:]...)[:len(rowData.C)-1]
				break
778 779 780
			}
		}
	}
781
	return f.adjustHelper(sheet, columns, num, -1)
782 783
}

784
// convertColWidthToPixels provides function to convert the width of a cell
xurime's avatar
xurime 已提交
785 786 787
// from user's units to pixels. Excel rounds the column width to the nearest
// pixel. If the width hasn't been set by the user we use the default value.
// If the column is hidden it has a value of zero.
788 789 790 791 792 793 794 795 796 797 798 799 800 801
func convertColWidthToPixels(width float64) float64 {
	var padding float64 = 5
	var pixels float64
	var maxDigitWidth float64 = 7
	if width == 0 {
		return pixels
	}
	if width < 1 {
		pixels = (width * 12) + 0.5
		return math.Ceil(pixels)
	}
	pixels = (width*maxDigitWidth + 0.5) + padding
	return math.Ceil(pixels)
}