cell.go 11.8 KB
Newer Older
xurime's avatar
xurime 已提交
1 2 3
package excelize

import (
4 5
	"encoding/xml"
	"fmt"
xurime's avatar
xurime 已提交
6 7
	"strconv"
	"strings"
8
	"time"
xurime's avatar
xurime 已提交
9 10
)

xurime's avatar
xurime 已提交
11 12
// mergeCellsParser provides function to check merged cells in worksheet by
// given axis.
13 14
func (f *File) mergeCellsParser(xlsx *xlsxWorksheet, axis string) string {
	axis = strings.ToUpper(axis)
15 16 17 18 19 20 21
	if xlsx.MergeCells != nil {
		for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
			if checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref) {
				axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
			}
		}
	}
22
	return axis
xurime's avatar
xurime 已提交
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 68 69 70 71
// SetCellValue provides function to set value of a cell. The following shows
// the supported data types:
//
//    int
//    int8
//    int16
//    int32
//    int64
//    float32
//    float64
//    string
//    []byte
//    time.Time
//    nil
//
// Note that default date format is m/d/yy h:mm of time.Time type value. You can
// set numbers format by SetCellStyle() method.
func (f *File) SetCellValue(sheet, axis string, value interface{}) {
	switch t := value.(type) {
	case int:
		f.SetCellInt(sheet, axis, value.(int))
	case int8:
		f.SetCellInt(sheet, axis, int(value.(int8)))
	case int16:
		f.SetCellInt(sheet, axis, int(value.(int16)))
	case int32:
		f.SetCellInt(sheet, axis, int(value.(int32)))
	case int64:
		f.SetCellInt(sheet, axis, int(value.(int64)))
	case float32:
		f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(value.(float32)), 'f', -1, 32))
	case float64:
		f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(value.(float64)), 'f', -1, 64))
	case string:
		f.SetCellStr(sheet, axis, t)
	case []byte:
		f.SetCellStr(sheet, axis, string(t))
	case time.Time:
		f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(timeToExcelTime(timeToUTCTime(value.(time.Time)))), 'f', -1, 32))
		f.setDefaultTimeStyle(sheet, axis)
	case nil:
		f.SetCellStr(sheet, axis, "")
	default:
		f.SetCellStr(sheet, axis, fmt.Sprintf("%v", value))
	}
}

xurime's avatar
xurime 已提交
72 73 74 75 76 77
// GetCellValue provides function to get formatted value from cell by given
// sheet index and axis in XLSX file. If it is possible to apply a format to the
// cell value, it will do so, if not then an error will be returned, along with
// the raw value of the cell.
func (f *File) GetCellValue(sheet, axis string) string {
	xlsx := f.workSheetReader(sheet)
78
	axis = f.mergeCellsParser(xlsx, axis)
79 80
	row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
	xAxis := row - 1
xurime's avatar
xurime 已提交
81
	rows := len(xlsx.SheetData.Row)
xurime's avatar
xurime 已提交
82 83 84 85 86 87
	if rows > 1 {
		lastRow := xlsx.SheetData.Row[rows-1].R
		if lastRow >= rows {
			rows = lastRow
		}
	}
88
	if rows < xAxis {
89
		return ""
xurime's avatar
xurime 已提交
90 91 92 93 94 95 96 97 98 99 100
	}
	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":
101
				shardStrings := f.sharedStringsReader()
xurime's avatar
xurime 已提交
102 103
				xlsxSI := 0
				xlsxSI, _ = strconv.Atoi(r.V)
104
				return f.formattedValue(r.S, shardStrings.SI[xlsxSI].T)
xurime's avatar
xurime 已提交
105
			case "str":
106
				return f.formattedValue(r.S, r.V)
xurime's avatar
xurime 已提交
107
			default:
108
				return f.formattedValue(r.S, r.V)
xurime's avatar
xurime 已提交
109 110 111
			}
		}
	}
112
	return ""
xurime's avatar
xurime 已提交
113 114
}

115 116 117 118 119 120 121
// formattedValue provides function to returns a value after formatted. If it is
// possible to apply a format to the cell value, it will do so, if not then an
// error will be returned, along with the raw value of the cell.
func (f *File) formattedValue(s int, v string) string {
	if s == 0 {
		return v
	}
122
	styleSheet := f.stylesReader()
123 124 125 126 127
	ok := builtInNumFmtFunc[styleSheet.CellXfs.Xf[s].NumFmtID]
	if ok != nil {
		return ok(styleSheet.CellXfs.Xf[s].NumFmtID, v)
	}
	return v
128 129
}

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
// GetCellStyle provides function to get cell style index by given worksheet
// name and cell coordinates.
func (f *File) GetCellStyle(sheet, axis string) int {
	xlsx := f.workSheetReader(sheet)
	axis = f.mergeCellsParser(xlsx, axis)
	col := string(strings.Map(letterOnlyMapF, axis))
	row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
	xAxis := row - 1
	yAxis := TitleToNumber(col)

	rows := xAxis + 1
	cell := yAxis + 1

	completeRow(xlsx, rows, cell)
	completeCol(xlsx, rows, cell)

	return f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
}

149 150
// GetCellFormula provides function to get formula from cell by given sheet
// index and axis in XLSX file.
151
func (f *File) GetCellFormula(sheet, axis string) string {
xurime's avatar
xurime 已提交
152
	xlsx := f.workSheetReader(sheet)
153
	axis = f.mergeCellsParser(xlsx, axis)
154 155
	row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
	xAxis := row - 1
xurime's avatar
xurime 已提交
156 157 158 159 160 161 162
	rows := len(xlsx.SheetData.Row)
	if rows > 1 {
		lastRow := xlsx.SheetData.Row[rows-1].R
		if lastRow >= rows {
			rows = lastRow
		}
	}
163
	if rows < xAxis {
164
		return ""
xurime's avatar
xurime 已提交
165
	}
xurime's avatar
xurime 已提交
166 167 168 169 170 171 172 173 174 175
	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 已提交
176 177 178
			}
		}
	}
179
	return ""
xurime's avatar
xurime 已提交
180
}
181 182 183 184

// SetCellFormula provides function to set cell formula by given string and
// sheet index.
func (f *File) SetCellFormula(sheet, axis, formula string) {
xurime's avatar
xurime 已提交
185
	xlsx := f.workSheetReader(sheet)
186
	axis = f.mergeCellsParser(xlsx, axis)
187 188 189
	col := string(strings.Map(letterOnlyMapF, axis))
	row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
	xAxis := row - 1
190
	yAxis := TitleToNumber(col)
191 192 193 194

	rows := xAxis + 1
	cell := yAxis + 1

xurime's avatar
xurime 已提交
195 196
	completeRow(xlsx, rows, cell)
	completeCol(xlsx, rows, cell)
197 198 199 200 201 202 203 204 205 206

	if xlsx.SheetData.Row[xAxis].C[yAxis].F != nil {
		xlsx.SheetData.Row[xAxis].C[yAxis].F.Content = formula
	} else {
		f := xlsxF{
			Content: formula,
		}
		xlsx.SheetData.Row[xAxis].C[yAxis].F = &f
	}
}
207 208 209 210

// SetCellHyperLink provides function to set cell hyperlink by given sheet index
// and link URL address. Only support external link currently.
func (f *File) SetCellHyperLink(sheet, axis, link string) {
xurime's avatar
xurime 已提交
211
	xlsx := f.workSheetReader(sheet)
212
	axis = f.mergeCellsParser(xlsx, axis)
213 214 215 216 217 218 219 220 221 222 223 224 225
	rID := f.addSheetRelationships(sheet, SourceRelationshipHyperLink, link, "External")
	hyperlink := xlsxHyperlink{
		Ref: axis,
		RID: "rId" + strconv.Itoa(rID),
	}
	if xlsx.Hyperlinks != nil {
		xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink, hyperlink)
	} else {
		hyperlinks := xlsxHyperlinks{}
		hyperlinks.Hyperlink = append(hyperlinks.Hyperlink, hyperlink)
		xlsx.Hyperlinks = &hyperlinks
	}
}
xurime's avatar
xurime 已提交
226

227 228
// MergeCell provides function to merge cells by given coordinate area and sheet
// name. For example create a merged cell of D3:E9 on Sheet1:
xurime's avatar
xurime 已提交
229
//
230
//    xlsx.MergeCell("sheet1", "D3", "E9")
xurime's avatar
xurime 已提交
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
//
// If you create a merged cell that overlaps with another existing merged cell,
// those merged cells that already exist will be removed.
func (f *File) MergeCell(sheet, hcell, vcell string) {
	if hcell == vcell {
		return
	}

	hcell = strings.ToUpper(hcell)
	vcell = strings.ToUpper(vcell)

	// Coordinate conversion, convert C1:B3 to 2,0,1,2.
	hcol := string(strings.Map(letterOnlyMapF, hcell))
	hrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, hcell))
	hyAxis := hrow - 1
246
	hxAxis := TitleToNumber(hcol)
xurime's avatar
xurime 已提交
247 248 249 250

	vcol := string(strings.Map(letterOnlyMapF, vcell))
	vrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, vcell))
	vyAxis := vrow - 1
251
	vxAxis := TitleToNumber(vcol)
xurime's avatar
xurime 已提交
252 253 254 255 256 257 258 259 260 261 262

	if vxAxis < hxAxis {
		hcell, vcell = vcell, hcell
		vxAxis, hxAxis = hxAxis, vxAxis
	}

	if vyAxis < hyAxis {
		hcell, vcell = vcell, hcell
		vyAxis, hyAxis = hyAxis, vyAxis
	}

xurime's avatar
xurime 已提交
263
	xlsx := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
264 265 266
	if xlsx.MergeCells != nil {
		mergeCell := xlsxMergeCell{}
		// Correct the coordinate area, such correct C1:B3 to B1:C3.
267
		mergeCell.Ref = ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
xurime's avatar
xurime 已提交
268 269 270 271 272 273 274 275 276 277 278 279
		// Delete the merged cells of the overlapping area.
		for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
			if checkCellInArea(hcell, xlsx.MergeCells.Cells[i].Ref) || checkCellInArea(strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0], mergeCell.Ref) {
				xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:i], xlsx.MergeCells.Cells[i+1:]...)
			} else if checkCellInArea(vcell, xlsx.MergeCells.Cells[i].Ref) || checkCellInArea(strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[1], mergeCell.Ref) {
				xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:i], xlsx.MergeCells.Cells[i+1:]...)
			}
		}
		xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells, &mergeCell)
	} else {
		mergeCell := xlsxMergeCell{}
		// Correct the coordinate area, such correct C1:B3 to B1:C3.
280
		mergeCell.Ref = ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
xurime's avatar
xurime 已提交
281 282 283 284 285 286
		mergeCells := xlsxMergeCells{}
		mergeCells.Cells = append(mergeCells.Cells, &mergeCell)
		xlsx.MergeCells = &mergeCells
	}
}

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 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 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
// SetCellInt provides function to set int type value of a cell by given
// worksheet name, cell coordinates and cell value.
func (f *File) SetCellInt(sheet, axis string, value int) {
	xlsx := f.workSheetReader(sheet)
	axis = f.mergeCellsParser(xlsx, axis)
	col := string(strings.Map(letterOnlyMapF, axis))
	row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
	xAxis := row - 1
	yAxis := TitleToNumber(col)

	rows := xAxis + 1
	cell := yAxis + 1

	completeRow(xlsx, rows, cell)
	completeCol(xlsx, rows, cell)

	xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
	xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
	xlsx.SheetData.Row[xAxis].C[yAxis].V = strconv.Itoa(value)
}

// prepareCellStyle provides function to prepare style index of cell in
// worksheet by given column index and style index.
func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int {
	if xlsx.Cols != nil && style == 0 {
		for _, v := range xlsx.Cols.Col {
			if v.Min <= col && col <= v.Max {
				style = v.Style
			}
		}
	}
	return style
}

// SetCellStr provides function to set string type value of a cell. Total number
// of characters that a cell can contain 32767 characters.
func (f *File) SetCellStr(sheet, axis, value string) {
	xlsx := f.workSheetReader(sheet)
	axis = f.mergeCellsParser(xlsx, axis)
	if len(value) > 32767 {
		value = value[0:32767]
	}
	col := string(strings.Map(letterOnlyMapF, axis))
	row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
	xAxis := row - 1
	yAxis := TitleToNumber(col)

	rows := xAxis + 1
	cell := yAxis + 1

	completeRow(xlsx, rows, cell)
	completeCol(xlsx, rows, cell)

	// Leading space(s) character detection.
	if len(value) > 0 {
		if value[0] == 32 {
			xlsx.SheetData.Row[xAxis].C[yAxis].XMLSpace = xml.Attr{
				Name:  xml.Name{Space: NameSpaceXML, Local: "space"},
				Value: "preserve",
			}
		}
	}
	xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
	xlsx.SheetData.Row[xAxis].C[yAxis].T = "str"
	xlsx.SheetData.Row[xAxis].C[yAxis].V = value
}

// SetCellDefault provides function to set string type value of a cell as
// default format without escaping the cell.
func (f *File) SetCellDefault(sheet, axis, value string) {
	xlsx := f.workSheetReader(sheet)
	axis = f.mergeCellsParser(xlsx, axis)
	col := string(strings.Map(letterOnlyMapF, axis))
	row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
	xAxis := row - 1
	yAxis := TitleToNumber(col)

	rows := xAxis + 1
	cell := yAxis + 1

	completeRow(xlsx, rows, cell)
	completeCol(xlsx, rows, cell)

	xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
	xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
	xlsx.SheetData.Row[xAxis].C[yAxis].V = value
}

xurime's avatar
xurime 已提交
375 376 377 378 379 380 381 382
// checkCellInArea provides function to determine if a given coordinate is
// within an area.
func checkCellInArea(cell, area string) bool {
	result := false
	cell = strings.ToUpper(cell)
	col := string(strings.Map(letterOnlyMapF, cell))
	row, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
	xAxis := row - 1
383
	yAxis := TitleToNumber(col)
xurime's avatar
xurime 已提交
384 385 386 387 388

	ref := strings.Split(area, ":")
	hCol := string(strings.Map(letterOnlyMapF, ref[0]))
	hRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, ref[0]))
	hyAxis := hRow - 1
389
	hxAxis := TitleToNumber(hCol)
xurime's avatar
xurime 已提交
390 391 392 393

	vCol := string(strings.Map(letterOnlyMapF, ref[1]))
	vRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, ref[1]))
	vyAxis := vRow - 1
394
	vxAxis := TitleToNumber(vCol)
xurime's avatar
xurime 已提交
395 396 397 398 399 400 401

	if hxAxis <= yAxis && yAxis <= vxAxis && hyAxis <= xAxis && xAxis <= vyAxis {
		result = true
	}

	return result
}