From b25ec6e9d3adfd329a1808ea70354deb38f94225 Mon Sep 17 00:00:00 2001 From: dvelderp Date: Thu, 25 Jan 2018 18:06:40 +0100 Subject: [PATCH] xlsx.SetCellValue() now supports bool value --- cell.go | 31 +++++++++++++++++++++++++++++++ excelize_test.go | 15 +++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/cell.go b/cell.go index bb363aa..808c413 100644 --- a/cell.go +++ b/cell.go @@ -41,6 +41,7 @@ func (f *File) mergeCellsParser(xlsx *xlsxWorksheet, axis string) string { // []byte // time.Duration // time.Time +// bool // nil // // Note that default date format is m/d/yy h:mm of time.Time type value. You can @@ -63,6 +64,8 @@ func (f *File) SetCellValue(sheet, axis string, value interface{}) { f.setDefaultTimeStyle(sheet, axis, 22) case nil: f.SetCellStr(sheet, axis, "") + case bool: + f.SetCellBool(sheet, axis, bool(value.(bool))) default: f.setCellIntValue(sheet, axis, value) } @@ -96,6 +99,34 @@ func (f *File) setCellIntValue(sheet, axis string, value interface{}) { } } +// SetCellBool provides function to set bool type value of a cell by given +// worksheet name, cell coordinates and cell value. +func (f *File) SetCellBool(sheet, axis string, value bool) { + xlsx := f.workSheetReader(sheet) + axis = f.mergeCellsParser(xlsx, axis) + col := string(strings.Map(letterOnlyMapF, axis)) + row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis)) + if err != nil { + return + } + 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 = "b" + if value { + xlsx.SheetData.Row[xAxis].C[yAxis].V = "1" + } else { + xlsx.SheetData.Row[xAxis].C[yAxis].V = "0" + } +} + // GetCellValue provides function to get formatted value from cell by given // worksheet name 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 diff --git a/excelize_test.go b/excelize_test.go index a4dc287..c7fb5de 100644 --- a/excelize_test.go +++ b/excelize_test.go @@ -81,6 +81,21 @@ func TestOpenFile(t *testing.T) { xlsx.SetCellValue("Sheet2", "F14", uint32(1<<32-1)) xlsx.SetCellValue("Sheet2", "F15", uint64(1<<32-1)) xlsx.SetCellValue("Sheet2", "F16", true) + // Test boolean write + booltest := []struct { + value bool + expected string + }{ + {false, "0"}, + {true, "1"}, + } + for _, test := range booltest { + xlsx.SetCellValue("Sheet2", "F16", test.value) + value := xlsx.GetCellValue("Sheet2", "F16") + if value != test.expected { + t.Errorf(`Expecting result of xlsx.SetCellValue("Sheet2", "F16", %v) to be %v (false), got: %s `, test.value, test.expected, value) + } + } xlsx.SetCellValue("Sheet2", "G2", nil) xlsx.SetCellValue("Sheet2", "G4", time.Now()) // 02:46:40