From 635ec33576b68a5264007ffc4a1027e0558a47da Mon Sep 17 00:00:00 2001 From: Valery Ozarnichuk Date: Wed, 12 Apr 2023 03:17:10 +0300 Subject: [PATCH] Support checking cell value length with multi-bytes characters (#1517) --- cell.go | 9 +++++---- cell_test.go | 13 +++++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/cell.go b/cell.go index 3f1e6529..1f01ce36 100644 --- a/cell.go +++ b/cell.go @@ -20,6 +20,7 @@ import ( "strconv" "strings" "time" + "unicode/utf8" ) // CellType is the type of cell value type. @@ -397,8 +398,8 @@ func (f *File) SetCellStr(sheet, cell, value string) error { // setCellString provides a function to set string type to shared string // table. func (f *File) setCellString(value string) (t, v string, err error) { - if len(value) > TotalCellChars { - value = value[:TotalCellChars] + if utf8.RuneCountInString(value) > TotalCellChars { + value = string([]rune(value)[:TotalCellChars]) } t = "s" var si int @@ -458,8 +459,8 @@ func (f *File) setSharedString(val string) (int, error) { // trimCellValue provides a function to set string type to cell. func trimCellValue(value string) (v string, ns xml.Attr) { - if len(value) > TotalCellChars { - value = value[:TotalCellChars] + if utf8.RuneCountInString(value) > TotalCellChars { + value = string([]rune(value)[:TotalCellChars]) } if len(value) > 0 { prefix, suffix := value[0], value[len(value)-1] diff --git a/cell_test.go b/cell_test.go index 565c1c93..8f731b12 100644 --- a/cell_test.go +++ b/cell_test.go @@ -176,6 +176,19 @@ func TestSetCellFloat(t *testing.T) { assert.EqualError(t, f.SetCellFloat("Sheet:1", "A1", 123.42, -1, 64), ErrSheetNameInvalid.Error()) } +func TestSetCellValuesMultiByte(t *testing.T) { + value := strings.Repeat("\u042B", TotalCellChars+1) + + f := NewFile() + err := f.SetCellValue("Sheet1", "A1", value) + assert.NoError(t, err) + + v, err := f.GetCellValue("Sheet1", "A1") + assert.NoError(t, err) + assert.NotEqual(t, value, v) + assert.Equal(t, TotalCellChars, len([]rune(v))) +} + func TestSetCellValue(t *testing.T) { f := NewFile() assert.EqualError(t, f.SetCellValue("Sheet1", "A", time.Now().UTC()), newCellNameToCoordinatesError("A", newInvalidCellNameError("A")).Error())