Browse Source

added functionality for writing a struct to a file, added tests

Eric 11 years ago
parent
commit
27896558bf
2 changed files with 88 additions and 0 deletions
  1. 44 0
      write.go
  2. 44 0
      write_test.go

+ 44 - 0
write.go

@@ -0,0 +1,44 @@
+package xlsx
+
+import "reflect"
+
+// Writes a struct to row r. Accepts a pointer to struct type 'e',
+// and the number of columns to write, `cols`. Returns -1 if the 'e'
+// doesn't point to a struct, otherwise the number of columns written
+func (r *Row) WriteStruct(e interface{}, cols int) int {
+	if cols == 0 {
+		return cols
+	}
+
+	v := reflect.ValueOf(e).Elem()
+	if v.Kind() != reflect.Struct {
+		return -1 // bail if it's not a struct
+	}
+
+	n := v.NumField() // number of fields in struct
+	if cols < n && cols > 0 {
+		n = cols
+	}
+
+	var k int
+	for i := 0; i < n; i, k = i+1, k+1 {
+		f := v.Field(i).Kind()
+		cell := r.AddCell()
+
+		switch f {
+		case reflect.Int, reflect.Int8, reflect.Int16,
+			reflect.Int32, reflect.Int64:
+			cell.SetInt(v.Field(i).Interface().(int))
+		case reflect.String:
+			cell.SetString(v.Field(i).Interface().(string))
+		case reflect.Float64, reflect.Float32:
+			cell.SetFloat(v.Field(i).Interface().(float64))
+		case reflect.Bool:
+			cell.SetBool(v.Field(i).Interface().(bool))
+		default:
+			k-- // nothing set so reset to previous
+		}
+	}
+
+	return k
+}

+ 44 - 0
write_test.go

@@ -0,0 +1,44 @@
+package xlsx
+
+import (
+	. "gopkg.in/check.v1"
+)
+
+type WriteSuite struct{}
+
+var _ = Suite(&WriteSuite{})
+
+// Test if we can write a struct to a row
+func (r *RowSuite) TestWriteStruct(c *C) {
+	var f *File
+	f = NewFile()
+	sheet := f.AddSheet("Test1")
+	row := sheet.AddRow()
+	type e struct {
+		FirstName string
+		Age       int
+		GPA       float64
+		LikesPHP  bool
+	}
+	testStruct := e{
+		"Eric",
+		20,
+		3.94,
+		false,
+	}
+	row.WriteStruct(&testStruct, -1)
+	c.Assert(row, NotNil)
+
+	c0 := row.Cells[0].String()
+	c1, e1 := row.Cells[1].Int()
+	c2, e2 := row.Cells[2].Float()
+	c3 := row.Cells[3].Bool()
+
+	c.Assert(c0, Equals, "Eric")
+	c.Assert(c1, Equals, 20)
+	c.Assert(c2, Equals, 3.94)
+	c.Assert(c3, Equals, false)
+
+	c.Assert(e1, Equals, nil)
+	c.Assert(e2, Equals, nil)
+}