oficina / sheets Public

Fix Unicode currency display in imported spreadsheets

Preserve UTF-8 literals and render Google currency tokens without changing stored numbers or format codes. Cover currency sections, dates and XLSX round trips with synthetic tests.
Co-Authored-By: Codex <noreply@openai.com>
Codex pushed by codex agent, operated by paul@keymail.dev 8e82b8a57143143d4fa3962075969c48a3e3a10d parent 5fc14f2
6 files changed, +207 −15
  • internal/sheets/format/currency.go +73 −0
  • internal/sheets/format/currency_test.go +52 −0
  • internal/sheets/format/dates.go +11 −12
  • internal/sheets/format/format.go +4 −0
  • internal/sheets/format/section.go +13 −3
  • internal/sheets/xlsx/currency_test.go +54 −0

CI passed — run details

diff --git a/internal/sheets/format/currency.go b/internal/sheets/format/currency.go
new file mode 100644
index 0000000..dbdc475
--- /dev/null
+++ b/internal/sheets/format/currency.go
@@ -0,0 +1,73 @@
+package format
+
+import (
+ "strings"
+ "unicode"
+ "unicode/utf8"
+)
+
+// expandCurrency turns Google/Excel currency tokens into quoted literals
+// before date detection: the D in [$CAD] is a currency code, not a day.
+// Google ignores an optional hexadecimal locale suffix. Keep the stored
+// format unchanged; this normalization only controls display.
+// https://developers.google.com/workspace/sheets/api/guides/formats
+func expandCurrency(section string) string {
+ var out strings.Builder
+ quoted := false
+ for i := 0; i < len(section); {
+ switch {
+ case section[i] == '\\' && i+1 < len(section):
+ _, size := utf8.DecodeRuneInString(section[i+1:])
+ out.WriteString(section[i : i+1+size])
+ i += 1 + size
+ case section[i] == '"':
+ quoted = !quoted
+ out.WriteByte(section[i])
+ i++
+ case !quoted && strings.HasPrefix(section[i:], "[$"):
+ end := strings.IndexByte(section[i+2:], ']')
+ if end >= 0 {
+ if symbol, ok := currencyLiteral(section[i+2 : i+2+end]); ok {
+ out.WriteByte('"')
+ out.WriteString(symbol)
+ out.WriteByte('"')
+ i += end + 3
+ continue
+ }
+ }
+ out.WriteByte(section[i])
+ i++
+ default:
+ out.WriteByte(section[i])
+ i++
+ }
+ }
+ return out.String()
+}
+
+func currencyLiteral(token string) (string, bool) {
+ symbol, locale, hasLocale := strings.Cut(token, "-")
+ if hasLocale {
+ if len(locale) == 0 || len(locale) > 8 {
+ return "", false
+ }
+ for _, r := range locale {
+ if !strings.ContainsRune("0123456789abcdefABCDEF", r) {
+ return "", false
+ }
+ }
+ }
+ r, size := utf8.DecodeRuneInString(symbol)
+ if size == len(symbol) && unicode.Is(unicode.Sc, r) {
+ return symbol, true
+ }
+ if len(symbol) != 3 {
+ return "", false
+ }
+ for _, r := range symbol {
+ if r < 'A' || r > 'Z' {
+ return "", false
+ }
+ }
+ return symbol, true
+}
diff --git a/internal/sheets/format/currency_test.go b/internal/sheets/format/currency_test.go
new file mode 100644
index 0000000..dc4dbb5
--- /dev/null
+++ b/internal/sheets/format/currency_test.go
@@ -0,0 +1,52 @@
+package format
+
+import "testing"
+
+func TestDisplayCurrencySymbols(t *testing.T) {
+ for _, tc := range []struct{ code, want string }{
+ {`€#,##0.00`, "€1,234.50"},
+ {`\€#,##0.00`, "€1,234.50"},
+ {`[$€]#,##0.00`, "€1,234.50"},
+ {`[$£]#,##0.00`, "£1,234.50"},
+ {`[$$]#,##0.00`, "$1,234.50"},
+ {`[$CAD]#,##0.00`, "CAD1,234.50"},
+ {`[$CAD-1009]#,##0.00`, "CAD1,234.50"},
+ {`[$€-407]#,##0.00`, "€1,234.50"},
+ {`#,##0.00[$€]`, "1,234.50€"},
+ {`"[$€]"#,##0.00`, "[$€]1,234.50"},
+ {`\[$€]#,##0.00`, "[$€]1,234.50"},
+ } {
+ t.Run(tc.code, func(t *testing.T) {
+ if got := Display(numValue(1234.5), tc.code); got != tc.want {
+ t.Fatalf("Display = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestCurrencySectionsAndUnicodeDates(t *testing.T) {
+ for _, tc := range []struct {
+ code string
+ num float64
+ want string
+ }{
+ {`[$€]0.00`, -12.5, "-€12.50"},
+ {`[$€]0.00;([$€]0.00);"zero"`, -12.5, "(€12.50)"},
+ {`[$€]0.00;([$€]0.00);"zero"`, 0, "zero"},
+ {`[$CAD]`, -12.5, "CAD"},
+ {`yyyy年mm月dd日`, 1, "1899年12月31日"},
+ {`yyyy\年mm\月dd\日`, 1, "1899年12月31日"},
+ } {
+ if got := Display(numValue(tc.num), tc.code); got != tc.want {
+ t.Errorf("Display(%v, %q) = %q, want %q", tc.num, tc.code, got, tc.want)
+ }
+ }
+}
+
+func TestCurrencyExpansionDoesNotInterpretOtherSyntax(t *testing.T) {
+ for _, code := range []string{`[$]0`, `[$€-]0`, `[$€-garbage]0`, `[$€`, `[Red]0`, `[$"x"]0`, `[$€;0]`} {
+ if got := expandCurrency(code); got != code {
+ t.Errorf("unsupported currency token changed: %q -> %q", code, got)
+ }
+ }
+}
diff --git a/internal/sheets/format/dates.go b/internal/sheets/format/dates.go
index 514ce41..dcf760f 100644
--- a/internal/sheets/format/dates.go
+++ b/internal/sheets/format/dates.go
@@ -5,16 +5,13 @@ import (
"strconv"
"strings"
"time"
+ "unicode/utf8"
)
-// excelEpoch mirrors calc/fn_date.go's constant of the same name and
-// value: day zero in spreadsheet date-serial numbering (Dec 30, 1899).
-// format cannot reach calc's unexported var (its only allowed import
-// from calc is Value), so the value is restated here; it must stay in
-// lockstep with calc's, or a date serial stops rendering as the
-// calendar date that produced it. See calc/fn_date.go for why this
-// epoch (one day off "real" Dec 31, 1899) reproduces Excel's numbering
-// with ordinary calendar arithmetic, no fake-leap-day case needed.
+// excelEpoch mirrors calc/fn_date.go's unexported epoch: Dec 30, 1899.
+// Keep them in lockstep so a date serial renders as the date that produced
+// it. See calc/fn_date.go for why this reproduces Excel's numbering with
+// ordinary calendar arithmetic, without a fake-leap-day special case.
var excelEpoch = time.Date(1899, time.December, 30, 0, 0, 0, 0, time.UTC)
type dateTokKind int
@@ -57,8 +54,9 @@ func tokenizeDate(section string) ([]dateTok, bool) {
c := section[i]
switch {
case c == '\\' && i+1 < len(section):
- toks = append(toks, dateTok{kind: dtLiteral, lit: string(section[i+1])})
- i += 2
+ _, size := utf8.DecodeRuneInString(section[i+1:])
+ toks = append(toks, dateTok{kind: dtLiteral, lit: section[i+1 : i+1+size]})
+ i += 1 + size
case c == '"':
j := strings.IndexByte(section[i+1:], '"')
if j < 0 {
@@ -87,8 +85,9 @@ func tokenizeDate(section string) ([]dateTok, bool) {
case isASCIILetter(c):
return nil, false
default:
- toks = append(toks, dateTok{kind: dtLiteral, lit: string(c)})
- i++
+ _, size := utf8.DecodeRuneInString(section[i:])
+ toks = append(toks, dateTok{kind: dtLiteral, lit: section[i : i+size]})
+ i += size
}
}
return toks, true
diff --git a/internal/sheets/format/format.go b/internal/sheets/format/format.go
index 6e2e544..3190810 100644
--- a/internal/sheets/format/format.go
+++ b/internal/sheets/format/format.go
@@ -24,6 +24,10 @@
// percent (scales by 100), literal text via "quoted" runs or a
// \-escaped single character, and any other bare character as a
// literal (so a currency symbol like "€" or "$" needs no quoting).
+// - Currency literals containing one Unicode currency symbol or three
+// uppercase ASCII letters, such as [$€], [$$] and [$CAD], optionally with
+// a hexadecimal locale suffix ([$CAD-1009]); the suffix is ignored,
+// matching Google Sheets. The original format remains stored intact.
// - Up to four ';'-separated sections: positive;negative;zero;text,
// per Excel's own convention. With one section it is used for
// every number and a negative value gets an automatic "-" prefix
diff --git a/internal/sheets/format/section.go b/internal/sheets/format/section.go
index 6e41e1e..6718e90 100644
--- a/internal/sheets/format/section.go
+++ b/internal/sheets/format/section.go
@@ -1,6 +1,9 @@
package format
-import "strings"
+import (
+ "strings"
+ "unicode/utf8"
+)
// sectionMode classifies one ';'-separated format section so renderSection
// knows which tokenizer to run.
@@ -67,6 +70,7 @@ func walkBareRunes(section string, fn func(byte) bool) {
// fixed literal label — used to decide whether a single-section format
// gets an automatic "-" for a negative value.
func rendersNumber(section string) bool {
+ section = expandCurrency(section)
if strings.EqualFold(strings.TrimSpace(section), "General") {
return true
}
@@ -78,6 +82,7 @@ func rendersNumber(section string) bool {
// construct this package does not support, telling the caller to fall
// back to General.
func renderSection(section string, val float64) (string, bool) {
+ section = expandCurrency(section)
if strings.EqualFold(strings.TrimSpace(section), "General") {
return generalNumber(val), true
}
@@ -137,8 +142,9 @@ func walkLiteralAndPlaceholders(section string, onLiteral func(string), onOther
c := section[i]
switch {
case c == '\\' && i+1 < len(section):
- onLiteral(string(section[i+1]))
- i += 2
+ _, size := utf8.DecodeRuneInString(section[i+1:])
+ onLiteral(section[i+1 : i+1+size])
+ i += 1 + size
case c == '"':
j := strings.IndexByte(section[i+1:], '"')
if j < 0 {
@@ -148,6 +154,10 @@ func walkLiteralAndPlaceholders(section string, onLiteral func(string), onOther
onLiteral(section[i+1 : i+1+j])
i = i + 1 + j + 1
}
+ case c >= utf8.RuneSelf:
+ _, size := utf8.DecodeRuneInString(section[i:])
+ onLiteral(section[i : i+size])
+ i += size
default:
if onOther(c) {
return
diff --git a/internal/sheets/xlsx/currency_test.go b/internal/sheets/xlsx/currency_test.go
new file mode 100644
index 0000000..47fe3eb
--- /dev/null
+++ b/internal/sheets/xlsx/currency_test.go
@@ -0,0 +1,54 @@
+package xlsx_test
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/xuri/excelize/v2"
+
+ "amadan.net/oficina/sheets/internal/sheets/format"
+ "amadan.net/oficina/sheets/internal/sheets/xlsx"
+)
+
+// Synthetic workbook: retain Google's currency code and numeric value
+// across import/export, while displaying the symbol rather than its syntax.
+func TestImportedGoogleCurrencyDisplayAndRoundTrip(t *testing.T) {
+ f := excelize.NewFile()
+ defer f.Close()
+ code := `[$€]#,##0.00`
+ style, err := f.NewStyle(&excelize.Style{CustomNumFmt: &code})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := f.SetCellValue("Sheet1", "A1", 1234.5); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.SetCellStyle("Sheet1", "A1", "A1", style); err != nil {
+ t.Fatal(err)
+ }
+ buf, err := f.WriteToBuffer()
+ if err != nil {
+ t.Fatal(err)
+ }
+ first := importReader(t, buf)
+ var exported bytes.Buffer
+ if err := xlsx.Export(first, &exported); err != nil {
+ t.Fatal(err)
+ }
+ second := importReader(t, &exported)
+ if diff := diffTabs(t, first, second); diff != "" {
+ t.Fatalf("currency round trip changed cells: %s", diff)
+ }
+ styleOut := formatOf(t, second, 0, 0)
+ if styleOut.NumberFmt != code {
+ t.Fatalf("currency format changed: %q", styleOut.NumberFmt)
+ }
+ row, col, ok := cellAt(second, 0, 0)
+ if !ok {
+ t.Fatal("missing imported cell")
+ }
+ value := second.Value(row, col)
+ if value.Num != 1234.5 || format.Display(value, styleOut.NumberFmt) != "€1,234.50" {
+ t.Fatalf("currency value or display changed: %+v", value)
+ }
+}