Browse Source

Do not create a blank fill if no fill is specified in the style format

Michael W. Mitton 7 năm trước cách đây
mục cha
commit
5dd00b9a00
2 tập tin đã thay đổi với 41 bổ sung3 xóa
  1. 7 3
      styles.go
  2. 34 0
      styles_test.go

+ 7 - 3
styles.go

@@ -1907,9 +1907,11 @@ func (f *File) NewStyle(style string) (int, error) {
 	s.Borders.Border = append(s.Borders.Border, setBorders(fs))
 	borderID = s.Borders.Count - 1
 
-	s.Fills.Count++
-	s.Fills.Fill = append(s.Fills.Fill, setFills(fs, true))
-	fillID = s.Fills.Count - 1
+	if fill := setFills(fs, true); fill != nil {
+		s.Fills.Count++
+		s.Fills.Fill = append(s.Fills.Fill, fill)
+		fillID = s.Fills.Count - 1
+	}
 
 	applyAlignment, alignment := fs.Alignment != nil, setAlignment(fs)
 	applyProtection, protection := fs.Protection != nil, setProtection(fs)
@@ -2145,6 +2147,8 @@ func setFills(formatStyle *formatStyle, fg bool) *xlsxFill {
 			pattern.BgColor.RGB = getPaletteColor(formatStyle.Fill.Color[0])
 		}
 		fill.PatternFill = &pattern
+	default:
+		return nil
 	}
 	return &fill
 }

+ 34 - 0
styles_test.go

@@ -6,6 +6,40 @@ import (
 	"github.com/stretchr/testify/assert"
 )
 
+func TestStyleFill(t *testing.T) {
+	cases := []struct {
+		label      string
+		format     string
+		expectFill bool
+	}{{
+		label:      "no_fill",
+		format:     `{"alignment":{"wrap_text":true}}`,
+		expectFill: false,
+	}, {
+		label:      "fill",
+		format:     `{"fill":{"type":"pattern","pattern":1,"color":["#000000"]}}`,
+		expectFill: true,
+	}}
+
+	for _, testCase := range cases {
+		xl := NewFile()
+		const sheet = "Sheet1"
+
+		styleID, err := xl.NewStyle(testCase.format)
+		if err != nil {
+			t.Fatalf("%v", err)
+		}
+
+		styles := xl.stylesReader()
+		style := styles.CellXfs.Xf[styleID]
+		if testCase.expectFill {
+			assert.NotEqual(t, style.FillID, 0, testCase.label)
+		} else {
+			assert.Equal(t, style.FillID, 0, testCase.label)
+		}
+	}
+}
+
 func TestSetConditionalFormat(t *testing.T) {
 	cases := []struct {
 		label  string