Skip to content

Commit 635ec33

Browse files
authored
Support checking cell value length with multi-bytes characters (#1517)
1 parent 4196348 commit 635ec33

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

cell.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"strconv"
2121
"strings"
2222
"time"
23+
"unicode/utf8"
2324
)
2425

2526
// CellType is the type of cell value type.
@@ -397,8 +398,8 @@ func (f *File) SetCellStr(sheet, cell, value string) error {
397398
// setCellString provides a function to set string type to shared string
398399
// table.
399400
func (f *File) setCellString(value string) (t, v string, err error) {
400-
if len(value) > TotalCellChars {
401-
value = value[:TotalCellChars]
401+
if utf8.RuneCountInString(value) > TotalCellChars {
402+
value = string([]rune(value)[:TotalCellChars])
402403
}
403404
t = "s"
404405
var si int
@@ -458,8 +459,8 @@ func (f *File) setSharedString(val string) (int, error) {
458459

459460
// trimCellValue provides a function to set string type to cell.
460461
func trimCellValue(value string) (v string, ns xml.Attr) {
461-
if len(value) > TotalCellChars {
462-
value = value[:TotalCellChars]
462+
if utf8.RuneCountInString(value) > TotalCellChars {
463+
value = string([]rune(value)[:TotalCellChars])
463464
}
464465
if len(value) > 0 {
465466
prefix, suffix := value[0], value[len(value)-1]

cell_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,19 @@ func TestSetCellFloat(t *testing.T) {
176176
assert.EqualError(t, f.SetCellFloat("Sheet:1", "A1", 123.42, -1, 64), ErrSheetNameInvalid.Error())
177177
}
178178

179+
func TestSetCellValuesMultiByte(t *testing.T) {
180+
value := strings.Repeat("\u042B", TotalCellChars+1)
181+
182+
f := NewFile()
183+
err := f.SetCellValue("Sheet1", "A1", value)
184+
assert.NoError(t, err)
185+
186+
v, err := f.GetCellValue("Sheet1", "A1")
187+
assert.NoError(t, err)
188+
assert.NotEqual(t, value, v)
189+
assert.Equal(t, TotalCellChars, len([]rune(v)))
190+
}
191+
179192
func TestSetCellValue(t *testing.T) {
180193
f := NewFile()
181194
assert.EqualError(t, f.SetCellValue("Sheet1", "A", time.Now().UTC()), newCellNameToCoordinatesError("A", newInvalidCellNameError("A")).Error())

0 commit comments

Comments
 (0)