rows.go 18.3 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
// 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

A
ahmad 已提交
12 13 14
package excelize

import (
15
	"bytes"
A
ahmad 已提交
16
	"encoding/xml"
xurime's avatar
xurime 已提交
17
	"errors"
L
Lunny Xiao 已提交
18
	"fmt"
19 20
	"io"
	"log"
21
	"math"
22
	"strconv"
23 24

	"github.com/mohae/deepcopy"
A
ahmad 已提交
25 26
)

27 28
// GetRows return all the rows in a sheet by given worksheet name (case
// sensitive). For example:
29
//
30
//    rows, err := f.GetRows("Sheet1")
31
//    if err != nil {
xurime's avatar
xurime 已提交
32
//        fmt.Println(err)
33 34
//        return
//    }
35
//    for _, row := range rows {
36
//        for _, colCell := range row {
37
//            fmt.Print(colCell, "\t")
38
//        }
xurime's avatar
xurime 已提交
39
//        fmt.Println()
40 41
//    }
//
42
func (f *File) GetRows(sheet string) ([][]string, error) {
H
Harris 已提交
43
	rows, err := f.Rows(sheet)
xurime's avatar
xurime 已提交
44 45 46
	if err != nil {
		return nil, err
	}
H
Harris 已提交
47 48 49 50 51
	results := make([][]string, 0, 64)
	for rows.Next() {
		row, err := rows.Columns()
		if err != nil {
			break
52
		}
H
Harris 已提交
53
		results = append(results, row)
54
	}
H
Harris 已提交
55
	return results, nil
A
ahmad 已提交
56 57
}

58
// Rows defines an iterator to a sheet.
L
Lunny Xiao 已提交
59
type Rows struct {
60 61 62 63 64 65
	err                        error
	curRow, totalRow, stashRow int
	sheet                      string
	rows                       []xlsxRow
	f                          *File
	decoder                    *xml.Decoder
L
Lunny Xiao 已提交
66 67 68 69
}

// Next will return true if find the next row element.
func (rows *Rows) Next() bool {
D
ducquangkstn 已提交
70
	rows.curRow++
71
	return rows.curRow <= rows.totalRow
L
Lunny Xiao 已提交
72 73
}

74
// Error will return the error when the error occurs.
L
Lunny Xiao 已提交
75 76 77 78
func (rows *Rows) Error() error {
	return rows.err
}

79
// Columns return the current row's column values.
80
func (rows *Rows) Columns() ([]string, error) {
81
	var (
82 83 84 85
		err                 error
		inElement           string
		attrR, cellCol, row int
		columns             []string
86
	)
87 88 89 90 91

	if rows.stashRow >= rows.curRow {
		return columns, err
	}

L
Lunny Xiao 已提交
92
	d := rows.f.sharedStringsReader()
93 94 95 96 97 98 99 100 101
	for {
		token, _ := rows.decoder.Token()
		if token == nil {
			break
		}
		switch startElement := token.(type) {
		case xml.StartElement:
			inElement = startElement.Name.Local
			if inElement == "row" {
102 103 104 105 106 107 108
				row++
				if attrR, err = attrValToInt("r", startElement.Attr); attrR != 0 {
					row = attrR
				}
				if row > rows.curRow {
					rows.stashRow = row - 1
					return columns, err
109 110 111
				}
			}
			if inElement == "c" {
112
				cellCol++
113 114
				colCell := xlsxC{}
				_ = rows.decoder.DecodeElement(&colCell, &startElement)
115
				if colCell.R != "" {
116
					if cellCol, _, err = CellNameToCoordinates(colCell.R); err != nil {
117 118
						return columns, err
					}
119 120 121
				}
				blank := cellCol - len(columns)
				val, _ := colCell.getValueFrom(rows.f, d)
122
				columns = append(appendSpace(blank, columns), val)
123 124 125
			}
		case xml.EndElement:
			inElement = startElement.Name.Local
126 127 128 129
			if row == 0 {
				row = rows.curRow
			}
			if inElement == "row" && row+1 < rows.curRow {
130 131
				return columns, err
			}
132
		}
L
Lunny Xiao 已提交
133
	}
134
	return columns, err
L
Lunny Xiao 已提交
135 136
}

137 138 139 140 141 142 143 144
// appendSpace append blank characters to slice by given length and source slice.
func appendSpace(l int, s []string) []string {
	for i := 1; i < l; i++ {
		s = append(s, "")
	}
	return s
}

L
Lunny Xiao 已提交
145 146 147 148 149 150
// ErrSheetNotExist defines an error of sheet is not exist
type ErrSheetNotExist struct {
	SheetName string
}

func (err ErrSheetNotExist) Error() string {
151
	return fmt.Sprintf("sheet %s is not exist", string(err.SheetName))
L
Lunny Xiao 已提交
152 153
}

xurime's avatar
xurime 已提交
154 155
// Rows returns a rows iterator, used for streaming reading data for a
// worksheet with a large data. For example:
L
Lunny Xiao 已提交
156
//
xurime's avatar
xurime 已提交
157
//    rows, err := f.Rows("Sheet1")
158
//    if err != nil {
xurime's avatar
xurime 已提交
159
//        fmt.Println(err)
160 161
//        return
//    }
L
Lunny Xiao 已提交
162
//    for rows.Next() {
xurime's avatar
xurime 已提交
163
//        row, err := rows.Columns()
164
//        if err != nil {
xurime's avatar
xurime 已提交
165
//            fmt.Println(err)
166
//        }
167
//        for _, colCell := range row {
xurime's avatar
xurime 已提交
168
//            fmt.Print(colCell, "\t")
L
Lunny Xiao 已提交
169
//        }
xurime's avatar
xurime 已提交
170
//        fmt.Println()
L
Lunny Xiao 已提交
171 172 173 174 175 176 177
//    }
//
func (f *File) Rows(sheet string) (*Rows, error) {
	name, ok := f.sheetMap[trimSheetName(sheet)]
	if !ok {
		return nil, ErrSheetNotExist{sheet}
	}
178 179 180
	if f.Sheet[name] != nil {
		// flush data
		output, _ := xml.Marshal(f.Sheet[name])
181
		f.saveFileList(name, f.replaceNameSpaceBytes(name, output))
182 183
	}
	var (
184 185 186 187
		err       error
		inElement string
		row       int
		rows      Rows
188
	)
xurime's avatar
xurime 已提交
189
	decoder := f.xmlNewDecoder(bytes.NewReader(f.readXML(name)))
190 191 192 193 194 195 196 197 198
	for {
		token, _ := decoder.Token()
		if token == nil {
			break
		}
		switch startElement := token.(type) {
		case xml.StartElement:
			inElement = startElement.Name.Local
			if inElement == "row" {
199
				row++
200 201
				for _, attr := range startElement.Attr {
					if attr.Name.Local == "r" {
202
						row, err = strconv.Atoi(attr.Value)
203 204 205 206 207 208 209 210 211
						if err != nil {
							return &rows, err
						}
					}
				}
				rows.totalRow = row
			}
		default:
		}
L
Lunny Xiao 已提交
212
	}
213 214
	rows.f = f
	rows.sheet = name
xurime's avatar
xurime 已提交
215
	rows.decoder = f.xmlNewDecoder(bytes.NewReader(f.readXML(name)))
216
	return &rows, nil
L
Lunny Xiao 已提交
217 218
}

219 220
// SetRowHeight provides a function to set the height of a single row. For
// example, set the height of the first row in Sheet1:
N
Nikolas Silva 已提交
221
//
xurime's avatar
xurime 已提交
222
//    err := f.SetRowHeight("Sheet1", 1, 50)
N
Nikolas Silva 已提交
223
//
224
func (f *File) SetRowHeight(sheet string, row int, height float64) error {
225
	if row < 1 {
226
		return newInvalidRowNumberError(row)
227
	}
228 229 230
	if height > MaxRowHeight {
		return errors.New("the height of the row must be smaller than or equal to 409 points")
	}
231
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
232 233 234
	if err != nil {
		return err
	}
235

236
	prepareSheetXML(ws, 0, row)
237

238
	rowIdx := row - 1
239 240
	ws.SheetData.Row[rowIdx].Ht = height
	ws.SheetData.Row[rowIdx].CustomHeight = true
241
	return nil
N
Nikolas Silva 已提交
242 243
}

xurime's avatar
xurime 已提交
244
// getRowHeight provides a function to get row height in pixels by given sheet
245 246
// name and row index.
func (f *File) getRowHeight(sheet string, row int) int {
247 248 249
	ws, _ := f.workSheetReader(sheet)
	for i := range ws.SheetData.Row {
		v := &ws.SheetData.Row[i]
250 251 252 253 254 255 256 257
		if v.R == row+1 && v.Ht != 0 {
			return int(convertRowHeightToPixels(v.Ht))
		}
	}
	// Optimisation for when the row heights haven't changed.
	return int(defaultRowHeightPixels)
}

xurime's avatar
xurime 已提交
258
// GetRowHeight provides a function to get row height by given worksheet name
259 260
// and row index. For example, get the height of the first row in Sheet1:
//
xurime's avatar
xurime 已提交
261
//    height, err := f.GetRowHeight("Sheet1", 1)
262
//
263
func (f *File) GetRowHeight(sheet string, row int) (float64, error) {
264
	if row < 1 {
265
		return defaultRowHeightPixels, newInvalidRowNumberError(row)
266
	}
267 268
	var ht = defaultRowHeight
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
269
	if err != nil {
270 271 272 273
		return ht, err
	}
	if ws.SheetFormatPr != nil {
		ht = ws.SheetFormatPr.DefaultRowHeight
xurime's avatar
xurime 已提交
274
	}
275 276
	if row > len(ws.SheetData.Row) {
		return ht, nil // it will be better to use 0, but we take care with BC
277
	}
278
	for _, v := range ws.SheetData.Row {
279
		if v.R == row && v.Ht != 0 {
280
			return v.Ht, nil
281 282 283
		}
	}
	// Optimisation for when the row heights haven't changed.
284
	return ht, nil
285 286
}

xurime's avatar
xurime 已提交
287
// sharedStringsReader provides a function to get the pointer to the structure
288 289
// after deserialization of xl/sharedStrings.xml.
func (f *File) sharedStringsReader() *xlsxSST {
290
	var err error
291 292
	f.Lock()
	defer f.Unlock()
293
	relPath := f.getWorkbookRelsPath()
294 295
	if f.SharedStrings == nil {
		var sharedStrings xlsxSST
296
		ss := f.readXML("xl/sharedStrings.xml")
297 298 299 300
		if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(ss))).
			Decode(&sharedStrings); err != nil && err != io.EOF {
			log.Printf("xml decode error: %s", err)
		}
301 302 303
		if sharedStrings.UniqueCount == 0 {
			sharedStrings.UniqueCount = sharedStrings.Count
		}
304
		f.SharedStrings = &sharedStrings
305
		for i := range sharedStrings.SI {
306 307
			if sharedStrings.SI[i].T != nil {
				f.sharedStringsMap[sharedStrings.SI[i].T.Val] = i
308 309
			}
		}
310
		f.addContentTypePart(0, "sharedStrings")
311
		rels := f.relsReader(relPath)
312
		for _, rel := range rels.Relationships {
313
			if rel.Target == "/xl/sharedStrings.xml" {
314 315 316
				return f.SharedStrings
			}
		}
317 318
		// Update workbook.xml.rels
		f.addRels(relPath, SourceRelationshipSharedStrings, "/xl/sharedStrings.xml", "")
319
	}
320

321
	return f.SharedStrings
A
ahmad 已提交
322 323
}

xurime's avatar
xurime 已提交
324
// getValueFrom return a value from a column/row cell, this function is
325 326 327
// inteded to be used with for range on rows an argument with the spreadsheet
// opened file.
func (c *xlsxC) getValueFrom(f *File, d *xlsxSST) (string, error) {
328 329
	f.Lock()
	defer f.Unlock()
330
	switch c.T {
331
	case "s":
332
		if c.V != "" {
333
			xlsxSI := 0
334
			xlsxSI, _ = strconv.Atoi(c.V)
335
			if len(d.SI) > xlsxSI {
336
				return f.formattedValue(c.S, d.SI[xlsxSI].String()), nil
337
			}
338
		}
339
		return f.formattedValue(c.S, c.V), nil
340
	case "str":
341
		return f.formattedValue(c.S, c.V), nil
342
	case "inlineStr":
343 344
		if c.IS != nil {
			return f.formattedValue(c.S, c.IS.String()), nil
xurime's avatar
xurime 已提交
345
		}
346
		return f.formattedValue(c.S, c.V), nil
347
	default:
348
		if len(c.V) > 16 {
349
			val, err := roundPrecision(c.V)
350 351 352
			if err != nil {
				return "", err
			}
353 354
			if val != c.V {
				return f.formattedValue(c.S, val), nil
355 356
			}
		}
357
		return f.formattedValue(c.S, c.V), nil
358
	}
A
ahmad 已提交
359
}
360

361 362 363 364 365 366 367 368 369 370
// roundPrecision round precision for numeric.
func roundPrecision(value string) (result string, err error) {
	var num float64
	if num, err = strconv.ParseFloat(value, 64); err != nil {
		return
	}
	result = fmt.Sprintf("%g", math.Round(num*numericPrecision)/numericPrecision)
	return
}

371
// SetRowVisible provides a function to set visible of a single row by given
372
// worksheet name and Excel row number. For example, hide row 2 in Sheet1:
373
//
xurime's avatar
xurime 已提交
374
//    err := f.SetRowVisible("Sheet1", 2, false)
375
//
376
func (f *File) SetRowVisible(sheet string, row int, visible bool) error {
377
	if row < 1 {
378
		return newInvalidRowNumberError(row)
379
	}
380

381
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
382 383 384
	if err != nil {
		return err
	}
385 386
	prepareSheetXML(ws, 0, row)
	ws.SheetData.Row[row-1].Hidden = !visible
387
	return nil
388 389
}

390 391 392
// GetRowVisible provides a function to get visible of a single row by given
// worksheet name and Excel row number. For example, get visible state of row
// 2 in Sheet1:
393
//
xurime's avatar
xurime 已提交
394
//    visible, err := f.GetRowVisible("Sheet1", 2)
395
//
396
func (f *File) GetRowVisible(sheet string, row int) (bool, error) {
397
	if row < 1 {
398
		return false, newInvalidRowNumberError(row)
399 400
	}

401
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
402 403 404
	if err != nil {
		return false, err
	}
405
	if row > len(ws.SheetData.Row) {
406
		return false, nil
407
	}
408
	return !ws.SheetData.Row[row-1].Hidden, nil
409
}
410

411
// SetRowOutlineLevel provides a function to set outline level number of a
xurime's avatar
xurime 已提交
412 413
// single row by given worksheet name and Excel row number. The value of
// parameter 'level' is 1-7. For example, outline row 2 in Sheet1 to level 1:
414
//
xurime's avatar
xurime 已提交
415
//    err := f.SetRowOutlineLevel("Sheet1", 2, 1)
416
//
417
func (f *File) SetRowOutlineLevel(sheet string, row int, level uint8) error {
418
	if row < 1 {
419
		return newInvalidRowNumberError(row)
420
	}
xurime's avatar
xurime 已提交
421 422 423
	if level > 7 || level < 1 {
		return errors.New("invalid outline level")
	}
424
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
425 426 427
	if err != nil {
		return err
	}
428 429
	prepareSheetXML(ws, 0, row)
	ws.SheetData.Row[row-1].OutlineLevel = level
430
	return nil
431 432
}

xurime's avatar
xurime 已提交
433
// GetRowOutlineLevel provides a function to get outline level number of a
xurime's avatar
xurime 已提交
434 435
// single row by given worksheet name and Excel row number. For example, get
// outline number of row 2 in Sheet1:
436
//
xurime's avatar
xurime 已提交
437
//    level, err := f.GetRowOutlineLevel("Sheet1", 2)
438
//
439
func (f *File) GetRowOutlineLevel(sheet string, row int) (uint8, error) {
440
	if row < 1 {
441
		return 0, newInvalidRowNumberError(row)
442
	}
443
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
444 445 446
	if err != nil {
		return 0, err
	}
447
	if row > len(ws.SheetData.Row) {
448
		return 0, nil
449
	}
450
	return ws.SheetData.Row[row-1].OutlineLevel, nil
451 452
}

C
caozhiyi 已提交
453
// RemoveRow provides a function to remove single row by given worksheet name
454
// and Excel row number. For example, remove row 3 in Sheet1:
455
//
xurime's avatar
xurime 已提交
456
//    err := f.RemoveRow("Sheet1", 3)
457
//
458 459 460 461
// 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.
462
func (f *File) RemoveRow(sheet string, row int) error {
463
	if row < 1 {
464
		return newInvalidRowNumberError(row)
465 466
	}

467
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
468 469 470
	if err != nil {
		return err
	}
471
	if row > len(ws.SheetData.Row) {
472
		return f.adjustHelper(sheet, rows, row, -1)
473
	}
xurime's avatar
xurime 已提交
474
	keep := 0
475 476
	for rowIdx := 0; rowIdx < len(ws.SheetData.Row); rowIdx++ {
		v := &ws.SheetData.Row[rowIdx]
xurime's avatar
xurime 已提交
477
		if v.R != row {
478
			ws.SheetData.Row[keep] = *v
xurime's avatar
xurime 已提交
479
			keep++
480 481
		}
	}
482
	ws.SheetData.Row = ws.SheetData.Row[:keep]
xurime's avatar
xurime 已提交
483
	return f.adjustHelper(sheet, rows, row, -1)
484 485
}

486 487 488
// InsertRow provides a function to insert a new row after given Excel row
// number starting from 1. For example, create a new row before row 3 in
// Sheet1:
489
//
xurime's avatar
xurime 已提交
490
//    err := f.InsertRow("Sheet1", 3)
491
//
492 493 494 495
// 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.
496
func (f *File) InsertRow(sheet string, row int) error {
497
	if row < 1 {
498
		return newInvalidRowNumberError(row)
499
	}
500
	return f.adjustHelper(sheet, rows, row, 1)
501 502
}

503
// DuplicateRow inserts a copy of specified row (by its Excel row number) below
V
Veniamin Albaev 已提交
504
//
xurime's avatar
xurime 已提交
505
//    err := f.DuplicateRow("Sheet1", 2)
V
Veniamin Albaev 已提交
506
//
507 508 509 510
// 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.
511 512
func (f *File) DuplicateRow(sheet string, row int) error {
	return f.DuplicateRowTo(sheet, row, row+1)
513 514
}

515 516
// DuplicateRowTo inserts a copy of specified row by it Excel number
// to specified row position moving down exists rows after target position
517
//
xurime's avatar
xurime 已提交
518
//    err := f.DuplicateRowTo("Sheet1", 2, 7)
519
//
520 521 522 523
// 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.
524
func (f *File) DuplicateRowTo(sheet string, row, row2 int) error {
525
	if row < 1 {
526
		return newInvalidRowNumberError(row)
527
	}
528

529
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
530 531 532
	if err != nil {
		return err
	}
533
	if row > len(ws.SheetData.Row) || row2 < 1 || row == row2 {
534
		return nil
V
Veniamin Albaev 已提交
535 536
	}

537 538 539
	var ok bool
	var rowCopy xlsxRow

540
	for i, r := range ws.SheetData.Row {
V
Veniamin Albaev 已提交
541
		if r.R == row {
542
			rowCopy = deepcopy.Copy(ws.SheetData.Row[i]).(xlsxRow)
543
			ok = true
V
Veniamin Albaev 已提交
544 545 546
			break
		}
	}
547
	if !ok {
548
		return nil
549
	}
V
Veniamin Albaev 已提交
550

551 552 553
	if err := f.adjustHelper(sheet, rows, row2, 1); err != nil {
		return err
	}
554 555

	idx2 := -1
556
	for i, r := range ws.SheetData.Row {
557 558 559 560 561
		if r.R == row2 {
			idx2 = i
			break
		}
	}
562
	if idx2 == -1 && len(ws.SheetData.Row) >= row2 {
563
		return nil
V
Veniamin Albaev 已提交
564
	}
565 566 567 568

	rowCopy.C = append(make([]xlsxC, 0, len(rowCopy.C)), rowCopy.C...)
	f.ajustSingleRowDimensions(&rowCopy, row2)

V
Veniamin Albaev 已提交
569
	if idx2 != -1 {
570
		ws.SheetData.Row[idx2] = rowCopy
V
Veniamin Albaev 已提交
571
	} else {
572
		ws.SheetData.Row = append(ws.SheetData.Row, rowCopy)
V
Veniamin Albaev 已提交
573
	}
574
	return f.duplicateMergeCells(sheet, ws, row, row2)
575 576 577 578
}

// duplicateMergeCells merge cells in the destination row if there are single
// row merged cells in the copied row.
579 580
func (f *File) duplicateMergeCells(sheet string, ws *xlsxWorksheet, row, row2 int) error {
	if ws.MergeCells == nil {
581 582 583 584 585
		return nil
	}
	if row > row2 {
		row++
	}
586
	for _, rng := range ws.MergeCells.Cells {
587 588 589 590 591 592 593 594
		coordinates, err := f.areaRefToCoordinates(rng.Ref)
		if err != nil {
			return err
		}
		if coordinates[1] < row2 && row2 < coordinates[3] {
			return nil
		}
	}
595 596
	for i := 0; i < len(ws.MergeCells.Cells); i++ {
		areaData := ws.MergeCells.Cells[i]
597 598 599 600 601 602 603 604 605 606 607
		coordinates, _ := f.areaRefToCoordinates(areaData.Ref)
		x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
		if y1 == y2 && y1 == row {
			from, _ := CoordinatesToCellName(x1, row2)
			to, _ := CoordinatesToCellName(x2, row2)
			if err := f.MergeCell(sheet, from, to); err != nil {
				return err
			}
			i++
		}
	}
608
	return nil
V
Veniamin Albaev 已提交
609 610
}

xurime's avatar
xurime 已提交
611 612
// checkRow provides a function to check and fill each column element for all
// rows and make that is continuous in a worksheet of XML. For example:
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
//
//    <row r="15" spans="1:22" x14ac:dyDescent="0.2">
//        <c r="A15" s="2" />
//        <c r="B15" s="2" />
//        <c r="F15" s="1" />
//        <c r="G15" s="1" />
//    </row>
//
// in this case, we should to change it to
//
//    <row r="15" spans="1:22" x14ac:dyDescent="0.2">
//        <c r="A15" s="2" />
//        <c r="B15" s="2" />
//        <c r="C15" s="2" />
//        <c r="D15" s="2" />
//        <c r="E15" s="2" />
//        <c r="F15" s="1" />
//        <c r="G15" s="1" />
//    </row>
//
// Noteice: this method could be very slow for large spreadsheets (more than
// 3000 rows one sheet).
635 636 637
func checkRow(ws *xlsxWorksheet) error {
	for rowIdx := range ws.SheetData.Row {
		rowData := &ws.SheetData.Row[rowIdx]
638

639 640 641
		colCount := len(rowData.C)
		if colCount == 0 {
			continue
642
		}
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
		// check and fill the cell without r attribute in a row element
		rCount := 0
		for idx, cell := range rowData.C {
			rCount++
			if cell.R != "" {
				lastR, _, err := CellNameToCoordinates(cell.R)
				if err != nil {
					return err
				}
				if lastR > rCount {
					rCount = lastR
				}
				continue
			}
			rowData.C[idx].R, _ = CoordinatesToCellName(rCount, rowIdx+1)
		}
659 660 661 662
		lastCol, _, err := CellNameToCoordinates(rowData.C[colCount-1].R)
		if err != nil {
			return err
		}
663 664 665 666 667

		if colCount < lastCol {
			oldList := rowData.C
			newlist := make([]xlsxC, 0, lastCol)

668
			rowData.C = ws.SheetData.Row[rowIdx].C[:0]
669 670

			for colIdx := 0; colIdx < lastCol; colIdx++ {
671 672 673 674 675
				cellName, err := CoordinatesToCellName(colIdx+1, rowIdx+1)
				if err != nil {
					return err
				}
				newlist = append(newlist, xlsxC{R: cellName})
676 677 678 679 680 681
			}

			rowData.C = newlist

			for colIdx := range oldList {
				colData := &oldList[colIdx]
682 683 684 685
				colNum, _, err := CellNameToCoordinates(colData.R)
				if err != nil {
					return err
				}
686
				ws.SheetData.Row[rowIdx].C[colNum-1] = *colData
687 688 689
			}
		}
	}
690
	return nil
691 692
}

xurime's avatar
xurime 已提交
693 694 695
// convertRowHeightToPixels provides a function to convert the height of a
// cell from user's units to pixels. If the height hasn't been set by the user
// we use the default value. If the row is hidden it has a value of zero.
696 697 698 699 700 701 702 703
func convertRowHeightToPixels(height float64) float64 {
	var pixels float64
	if height == 0 {
		return pixels
	}
	pixels = math.Ceil(4.0 / 3.0 * height)
	return pixels
}