rows.go 12.6 KB
Newer Older
xurime's avatar
xurime 已提交
1 2 3 4 5 6 7 8
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// 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
// charts of XLSX. This library needs Go version 1.8 or later.
xurime's avatar
xurime 已提交
9

A
ahmad 已提交
10 11 12
package excelize

import (
13
	"bytes"
A
ahmad 已提交
14
	"encoding/xml"
L
Lunny Xiao 已提交
15 16
	"fmt"
	"io"
17
	"math"
18
	"strconv"
A
ahmad 已提交
19 20 21
	"strings"
)

22 23
// GetRows return all the rows in a sheet by given worksheet name (case
// sensitive). For example:
24
//
25
//    for _, row := range xlsx.GetRows("Sheet1") {
26 27 28 29 30 31 32
//        for _, colCell := range row {
//            fmt.Print(colCell, "\t")
//        }
//        fmt.Println()
//    }
//
func (f *File) GetRows(sheet string) [][]string {
xurime's avatar
xurime 已提交
33
	xlsx := f.workSheetReader(sheet)
34
	rows := [][]string{}
35 36 37 38
	name, ok := f.sheetMap[trimSheetName(sheet)]
	if !ok {
		return rows
	}
xurime's avatar
xurime 已提交
39 40
	if xlsx != nil {
		output, _ := xml.Marshal(f.Sheet[name])
41
		f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
A
ahmad 已提交
42
	}
43
	xml.NewDecoder(bytes.NewReader(f.readXML(name)))
44
	d := f.sharedStringsReader()
45
	var inElement string
xurime's avatar
xurime 已提交
46
	var r xlsxRow
47
	var row []string
48
	tr, tc := f.getTotalRowsCols(name)
xurime's avatar
xurime 已提交
49 50 51 52 53 54 55
	for i := 0; i < tr; i++ {
		row = []string{}
		for j := 0; j <= tc; j++ {
			row = append(row, "")
		}
		rows = append(rows, row)
	}
56
	decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
57 58 59 60 61 62 63 64 65
	for {
		token, _ := decoder.Token()
		if token == nil {
			break
		}
		switch startElement := token.(type) {
		case xml.StartElement:
			inElement = startElement.Name.Local
			if inElement == "row" {
xurime's avatar
xurime 已提交
66
				r = xlsxRow{}
67
				_ = decoder.DecodeElement(&r, &startElement)
xurime's avatar
xurime 已提交
68
				cr := r.R - 1
69
				for _, colCell := range r.C {
70
					c := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
71
					val, _ := colCell.getValueFrom(f, d)
xurime's avatar
xurime 已提交
72
					rows[cr][c] = val
73 74 75
				}
			}
		default:
76 77
		}
	}
78
	return rows
A
ahmad 已提交
79 80
}

L
Lunny Xiao 已提交
81 82 83 84 85 86 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
// Rows defines an iterator to a sheet
type Rows struct {
	decoder *xml.Decoder
	token   xml.Token
	err     error
	f       *File
}

// Next will return true if find the next row element.
func (rows *Rows) Next() bool {
	for {
		rows.token, rows.err = rows.decoder.Token()
		if rows.err == io.EOF {
			rows.err = nil
		}
		if rows.token == nil {
			return false
		}

		switch startElement := rows.token.(type) {
		case xml.StartElement:
			inElement := startElement.Name.Local
			if inElement == "row" {
				return true
			}
		}
	}
}

// Error will return the error when the find next row element
func (rows *Rows) Error() error {
	return rows.err
}

// Columns return the current row's column values
func (rows *Rows) Columns() []string {
	if rows.token == nil {
		return []string{}
	}
	startElement := rows.token.(xml.StartElement)
	r := xlsxRow{}
122
	_ = rows.decoder.DecodeElement(&r, &startElement)
L
Lunny Xiao 已提交
123
	d := rows.f.sharedStringsReader()
124
	row := make([]string, len(r.C))
L
Lunny Xiao 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
	for _, colCell := range r.C {
		c := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
		val, _ := colCell.getValueFrom(rows.f, d)
		row[c] = val
	}
	return row
}

// ErrSheetNotExist defines an error of sheet is not exist
type ErrSheetNotExist struct {
	SheetName string
}

func (err ErrSheetNotExist) Error() string {
	return fmt.Sprintf("Sheet %s is not exist", string(err.SheetName))
}

// Rows return a rows iterator. For example:
//
xurime's avatar
xurime 已提交
144
//    rows, err := xlsx.Rows("Sheet1")
L
Lunny Xiao 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158
//    for rows.Next() {
//        for _, colCell := range rows.Columns() {
//            fmt.Print(colCell, "\t")
//        }
//        fmt.Println()
//    }
//
func (f *File) Rows(sheet string) (*Rows, error) {
	xlsx := f.workSheetReader(sheet)
	name, ok := f.sheetMap[trimSheetName(sheet)]
	if !ok {
		return nil, ErrSheetNotExist{sheet}
	}
	if xlsx != nil {
159
		output, _ := xml.Marshal(f.Sheet[name])
160
		f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
L
Lunny Xiao 已提交
161 162 163
	}
	return &Rows{
		f:       f,
164
		decoder: xml.NewDecoder(bytes.NewReader(f.readXML(name))),
L
Lunny Xiao 已提交
165 166 167
	}, nil
}

xurime's avatar
xurime 已提交
168
// getTotalRowsCols provides a function to get total columns and rows in a
169
// worksheet.
170
func (f *File) getTotalRowsCols(name string) (int, int) {
171
	decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
xurime's avatar
xurime 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184
	var inElement string
	var r xlsxRow
	var tr, tc int
	for {
		token, _ := decoder.Token()
		if token == nil {
			break
		}
		switch startElement := token.(type) {
		case xml.StartElement:
			inElement = startElement.Name.Local
			if inElement == "row" {
				r = xlsxRow{}
185
				_ = decoder.DecodeElement(&r, &startElement)
xurime's avatar
xurime 已提交
186 187
				tr = r.R
				for _, colCell := range r.C {
188
					col := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
xurime's avatar
xurime 已提交
189 190 191 192 193 194 195 196 197 198 199
					if col > tc {
						tc = col
					}
				}
			}
		default:
		}
	}
	return tr, tc
}

200 201
// 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 已提交
202
//
203
//    xlsx.SetRowHeight("Sheet1", 1, 50)
N
Nikolas Silva 已提交
204
//
205
func (f *File) SetRowHeight(sheet string, row int, height float64) {
xurime's avatar
xurime 已提交
206
	xlsx := f.workSheetReader(sheet)
N
Nikolas Silva 已提交
207
	cells := 0
208 209 210 211
	rowIdx := row - 1
	completeRow(xlsx, row, cells)
	xlsx.SheetData.Row[rowIdx].Ht = height
	xlsx.SheetData.Row[rowIdx].CustomHeight = true
N
Nikolas Silva 已提交
212 213
}

xurime's avatar
xurime 已提交
214
// getRowHeight provides a function to get row height in pixels by given sheet
215 216 217 218 219 220 221 222 223 224 225 226
// name and row index.
func (f *File) getRowHeight(sheet string, row int) int {
	xlsx := f.workSheetReader(sheet)
	for _, v := range xlsx.SheetData.Row {
		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 已提交
227
// GetRowHeight provides a function to get row height by given worksheet name
228 229 230 231
// and row index. For example, get the height of the first row in Sheet1:
//
//    xlsx.GetRowHeight("Sheet1", 1)
//
232 233 234
func (f *File) GetRowHeight(sheet string, row int) float64 {
	xlsx := f.workSheetReader(sheet)
	for _, v := range xlsx.SheetData.Row {
235
		if v.R == row && v.Ht != 0 {
236 237 238 239 240 241 242
			return v.Ht
		}
	}
	// Optimisation for when the row heights haven't changed.
	return defaultRowHeightPixels
}

xurime's avatar
xurime 已提交
243
// sharedStringsReader provides a function to get the pointer to the structure
244 245 246 247
// after deserialization of xl/sharedStrings.xml.
func (f *File) sharedStringsReader() *xlsxSST {
	if f.SharedStrings == nil {
		var sharedStrings xlsxSST
248
		ss := f.readXML("xl/sharedStrings.xml")
249
		if len(ss) == 0 {
250 251
			ss = f.readXML("xl/SharedStrings.xml")
		}
252
		_ = xml.Unmarshal(namespaceStrictToTransitional(ss), &sharedStrings)
253 254 255
		f.SharedStrings = &sharedStrings
	}
	return f.SharedStrings
A
ahmad 已提交
256 257
}

xurime's avatar
xurime 已提交
258 259 260
// getValueFrom return a value from a column/row cell, this function is
// inteded to be used with for range on rows an argument with the xlsx opened
// file.
261
func (xlsx *xlsxC) getValueFrom(f *File, d *xlsxSST) (string, error) {
262 263 264 265
	switch xlsx.T {
	case "s":
		xlsxSI := 0
		xlsxSI, _ = strconv.Atoi(xlsx.V)
xurime's avatar
xurime 已提交
266 267 268 269 270 271 272
		if len(d.SI[xlsxSI].R) > 0 {
			value := ""
			for _, v := range d.SI[xlsxSI].R {
				value += v.T
			}
			return value, nil
		}
273
		return f.formattedValue(xlsx.S, d.SI[xlsxSI].T), nil
274
	case "str":
275
		return f.formattedValue(xlsx.S, xlsx.V), nil
276 277
	case "inlineStr":
		return f.formattedValue(xlsx.S, xlsx.IS.T), nil
278
	default:
279
		return f.formattedValue(xlsx.S, xlsx.V), nil
280
	}
A
ahmad 已提交
281
}
282

283
// SetRowVisible provides a function to set visible of a single row by given
284
// worksheet name and row index. For example, hide row 2 in Sheet1:
285
//
286
//    xlsx.SetRowVisible("Sheet1", 2, false)
287
//
288
func (f *File) SetRowVisible(sheet string, rowIndex int, visible bool) {
289 290 291 292
	xlsx := f.workSheetReader(sheet)
	rows := rowIndex + 1
	cells := 0
	completeRow(xlsx, rows, cells)
293 294 295 296
	if visible {
		xlsx.SheetData.Row[rowIndex].Hidden = false
		return
	}
297 298 299
	xlsx.SheetData.Row[rowIndex].Hidden = true
}

300
// GetRowVisible provides a function to get visible of a single row by given
301
// worksheet name and row index. For example, get visible state of row 2 in
302
// Sheet1:
303
//
304
//    xlsx.GetRowVisible("Sheet1", 2)
305
//
306
func (f *File) GetRowVisible(sheet string, rowIndex int) bool {
307 308 309 310
	xlsx := f.workSheetReader(sheet)
	rows := rowIndex + 1
	cells := 0
	completeRow(xlsx, rows, cells)
311
	return !xlsx.SheetData.Row[rowIndex].Hidden
312
}
313

314 315 316
// SetRowOutlineLevel provides a function to set outline level number of a
// single row by given worksheet name and row index. For example, outline row
// 2 in Sheet1 to level 1:
317 318 319 320 321 322 323 324 325 326 327
//
//    xlsx.SetRowOutlineLevel("Sheet1", 2, 1)
//
func (f *File) SetRowOutlineLevel(sheet string, rowIndex int, level uint8) {
	xlsx := f.workSheetReader(sheet)
	rows := rowIndex + 1
	cells := 0
	completeRow(xlsx, rows, cells)
	xlsx.SheetData.Row[rowIndex].OutlineLevel = level
}

xurime's avatar
xurime 已提交
328 329 330
// GetRowOutlineLevel provides a function to get outline level number of a
// single row by given worksheet name and row index. For example, get outline
// number of row 2 in Sheet1:
331 332 333 334 335 336 337 338 339 340 341
//
//    xlsx.GetRowOutlineLevel("Sheet1", 2)
//
func (f *File) GetRowOutlineLevel(sheet string, rowIndex int) uint8 {
	xlsx := f.workSheetReader(sheet)
	rows := rowIndex + 1
	cells := 0
	completeRow(xlsx, rows, cells)
	return xlsx.SheetData.Row[rowIndex].OutlineLevel
}

xurime's avatar
xurime 已提交
342 343
// RemoveRow provides a function to remove single row by given worksheet name
// and row index. For example, remove row 3 in Sheet1:
344 345 346 347 348 349 350 351 352 353
//
//    xlsx.RemoveRow("Sheet1", 2)
//
func (f *File) RemoveRow(sheet string, row int) {
	if row < 0 {
		return
	}
	xlsx := f.workSheetReader(sheet)
	row++
	for i, r := range xlsx.SheetData.Row {
xurime's avatar
xurime 已提交
354 355 356 357
		if r.R == row {
			xlsx.SheetData.Row = append(xlsx.SheetData.Row[:i], xlsx.SheetData.Row[i+1:]...)
			f.adjustHelper(sheet, -1, row, -1)
			return
358 359 360 361
		}
	}
}

xurime's avatar
xurime 已提交
362 363
// InsertRow provides a function to insert a new row before given row index.
// For example, create a new row before row 3 in Sheet1:
364 365 366 367 368 369 370 371 372 373 374
//
//    xlsx.InsertRow("Sheet1", 2)
//
func (f *File) InsertRow(sheet string, row int) {
	if row < 0 {
		return
	}
	row++
	f.adjustHelper(sheet, -1, row, 1)
}

xurime's avatar
xurime 已提交
375 376
// 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:
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
//
//    <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).
func checkRow(xlsx *xlsxWorksheet) {
	buffer := bytes.Buffer{}
401 402
	for k := range xlsx.SheetData.Row {
		lenCol := len(xlsx.SheetData.Row[k].C)
xurime's avatar
xurime 已提交
403
		if lenCol > 0 {
404 405
			endR := string(strings.Map(letterOnlyMapF, xlsx.SheetData.Row[k].C[lenCol-1].R))
			endRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, xlsx.SheetData.Row[k].C[lenCol-1].R))
xurime's avatar
xurime 已提交
406 407 408 409 410
			endCol := TitleToNumber(endR) + 1
			if lenCol < endCol {
				oldRow := xlsx.SheetData.Row[k].C
				xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
				tmp := []xlsxC{}
411
				for i := 0; i < endCol; i++ {
xurime's avatar
xurime 已提交
412 413 414 415 416 417 418 419 420 421 422 423
					buffer.WriteString(ToAlphaString(i))
					buffer.WriteString(strconv.Itoa(endRow))
					tmp = append(tmp, xlsxC{
						R: buffer.String(),
					})
					buffer.Reset()
				}
				xlsx.SheetData.Row[k].C = tmp
				for _, y := range oldRow {
					colAxis := TitleToNumber(string(strings.Map(letterOnlyMapF, y.R)))
					xlsx.SheetData.Row[k].C[colAxis] = y
				}
424 425 426 427 428
			}
		}
	}
}

xurime's avatar
xurime 已提交
429
// completeRow provides a function to check and fill each column element for a
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
// single row and make that is continuous in a worksheet of XML by given row
// index and axis.
func completeRow(xlsx *xlsxWorksheet, row, cell int) {
	currentRows := len(xlsx.SheetData.Row)
	if currentRows > 1 {
		lastRow := xlsx.SheetData.Row[currentRows-1].R
		if lastRow >= row {
			row = lastRow
		}
	}
	for i := currentRows; i < row; i++ {
		xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
			R: i + 1,
		})
	}
	buffer := bytes.Buffer{}
	for ii := currentRows; ii < row; ii++ {
		start := len(xlsx.SheetData.Row[ii].C)
		if start == 0 {
			for iii := start; iii < cell; iii++ {
				buffer.WriteString(ToAlphaString(iii))
				buffer.WriteString(strconv.Itoa(ii + 1))
				xlsx.SheetData.Row[ii].C = append(xlsx.SheetData.Row[ii].C, xlsxC{
					R: buffer.String(),
				})
				buffer.Reset()
			}
		}
	}
}

xurime's avatar
xurime 已提交
461 462 463
// 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.
464 465 466 467 468 469 470 471
func convertRowHeightToPixels(height float64) float64 {
	var pixels float64
	if height == 0 {
		return pixels
	}
	pixels = math.Ceil(4.0 / 3.0 * height)
	return pixels
}