Support checking cell value length with multi-bytes characters (#1517)

This commit is contained in:
Valery Ozarnichuk 2023-04-12 03:17:10 +03:00 committed by GitHub
parent 4196348f9f
commit 635ec33576
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 4 deletions

View File

@ -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]

View File

@ -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())