write.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package xlsx
  2. import "reflect"
  3. // Writes a struct to row r. Accepts a pointer to struct type 'e',
  4. // and the number of columns to write, `cols`. Returns -1 if the 'e'
  5. // doesn't point to a struct, otherwise the number of columns written
  6. func (r *Row) WriteStruct(e interface{}, cols int) int {
  7. if cols == 0 {
  8. return cols
  9. }
  10. v := reflect.ValueOf(e).Elem()
  11. if v.Kind() != reflect.Struct {
  12. return -1 // bail if it's not a struct
  13. }
  14. n := v.NumField() // number of fields in struct
  15. if cols < n {
  16. n = cols
  17. }
  18. var k int
  19. for i := 0; i < n; i, k = i+1, k+1 {
  20. f := v.Field(i).Kind()
  21. cell := r.AddCell()
  22. switch f {
  23. case reflect.Int, reflect.Int8, reflect.Int16,
  24. reflect.Int32, reflect.Int64:
  25. cell.SetInt(v.Field(i).Interface().(int))
  26. case reflect.String:
  27. cell.SetString(v.Field(i).Interface().(string))
  28. case reflect.Float64, reflect.Float32:
  29. cell.SetFloat(v.Field(i).Interface().(float64))
  30. case reflect.Bool:
  31. cell.SetBool(v.Field(i).Interface().(bool))
  32. default:
  33. k-- // nothing set so reset to previous
  34. }
  35. }
  36. return k
  37. }