cell.go 1.9 KB
Newer Older
xurime's avatar
xurime 已提交
1 2 3 4 5 6 7 8
package excelize

import (
	"encoding/xml"
	"strconv"
	"strings"
)

xurime's avatar
xurime 已提交
9
// GetCellValue provide function get value from cell by given sheet index and axis in XLSX file.
xurime's avatar
xurime 已提交
10
// The value of the merged cell is not available currently.
11
func (f *File) GetCellValue(sheet string, axis string) string {
xurime's avatar
xurime 已提交
12 13
	axis = strings.ToUpper(axis)
	var xlsx xlsxWorksheet
14
	row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
xurime's avatar
xurime 已提交
15 16
	xAxis := row - 1
	name := `xl/worksheets/` + strings.ToLower(sheet) + `.xml`
17
	xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
xurime's avatar
xurime 已提交
18
	rows := len(xlsx.SheetData.Row)
xurime's avatar
xurime 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
	if rows > 1 {
		lastRow := xlsx.SheetData.Row[rows-1].R
		if lastRow >= rows {
			rows = lastRow
		}
	}
	if rows <= xAxis {
		return ``
	}
	for _, v := range xlsx.SheetData.Row {
		if v.R != row {
			continue
		}
		for _, r := range v.C {
			if axis != r.R {
				continue
			}
			switch r.T {
			case "s":
				shardStrings := xlsxSST{}
				xlsxSI := 0
				xlsxSI, _ = strconv.Atoi(r.V)
				xml.Unmarshal([]byte(f.readXML(`xl/sharedStrings.xml`)), &shardStrings)
				return shardStrings.SI[xlsxSI].T
			case "str":
				return r.V
			default:
				return r.V
			}
		}
	}
	return ``
}

// GetCellFormula provide function get formula from cell by given sheet index and axis in XLSX file.
func (f *File) GetCellFormula(sheet string, axis string) string {
	axis = strings.ToUpper(axis)
	var xlsx xlsxWorksheet
	row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
	xAxis := row - 1
	name := `xl/worksheets/` + strings.ToLower(sheet) + `.xml`
	xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
	rows := len(xlsx.SheetData.Row)
	if rows > 1 {
		lastRow := xlsx.SheetData.Row[rows-1].R
		if lastRow >= rows {
			rows = lastRow
		}
	}
xurime's avatar
xurime 已提交
68 69 70
	if rows <= xAxis {
		return ``
	}
xurime's avatar
xurime 已提交
71 72 73 74 75 76 77 78 79 80
	for _, v := range xlsx.SheetData.Row {
		if v.R != row {
			continue
		}
		for _, f := range v.C {
			if axis != f.R {
				continue
			}
			if f.F != nil {
				return f.F.Content
xurime's avatar
xurime 已提交
81 82 83 84 85
			}
		}
	}
	return ``
}