github.com/keysonzzz/kmg@v0.0.0-20151121023212-05317bfd7d39/kmg/SubCommand/Xlsx2Yaml.go.bak (about) 1 package command 2 3 /* 4 import ( 5 "flag" 6 "fmt" 7 8 "github.com/bronze1man/kmg/console" 9 "github.com/bronze1man/kmg/encoding/kmgExcel" 10 "github.com/bronze1man/kmg/encoding/kmgYaml" 11 ) 12 13 type Xlsx2Yaml struct { 14 filePath string 15 format string 16 isOutputAllSheet bool 17 } 18 19 func (command *Xlsx2Yaml) GetNameConfig() *console.NameConfig { 20 return &console.NameConfig{Name: "Xlsx2Yaml", 21 Short: "convert from xlsx(Microsoft excel 2007) to yaml", 22 } 23 } 24 func (command *Xlsx2Yaml) ConfigFlagSet(f *flag.FlagSet) { 25 f.StringVar(&command.filePath, "input", "", "input file path") 26 f.StringVar(&command.format, "format", "grid", "output yaml format(grid,raw)") 27 f.BoolVar(&command.isOutputAllSheet, "outputAllSheet", false, "is output all sheet(default just out first one)?") 28 } 29 func (command *Xlsx2Yaml) Execute(context *console.Context) error { 30 if command.filePath == "" { 31 if context.FlagSet().NArg() == 1 { 32 command.filePath = context.FlagSet().Arg(0) 33 } else { 34 return fmt.Errorf("need input file") 35 } 36 } 37 rawArray, err := kmgExcel.XlsxFile2Array(command.filePath) 38 if err != nil { 39 return err 40 } 41 output, err := command.formatOutput(rawArray) 42 if err != nil { 43 return err 44 } 45 outByte, err := kmgYaml.Marshal(output) 46 if err != nil { 47 return err 48 } 49 _, err = context.Stdout.Write(outByte) 50 if err != nil { 51 return err 52 } 53 return nil 54 } 55 56 func (command *Xlsx2Yaml) formatOutput(rawArray [][][]string) (interface{}, error) { 57 switch command.format { 58 case "raw": 59 if command.isOutputAllSheet { 60 return rawArray, nil 61 } else { 62 return rawArray[0], nil 63 } 64 case "grid": 65 o := [][]map[string]string{} 66 for _, s := range rawArray { 67 o1, err := kmgExcel.TitleArrayToGrid(s) 68 if err != nil { 69 return nil, err 70 } 71 o = append(o, o1) 72 } 73 if command.isOutputAllSheet { 74 return o, nil 75 } else { 76 return o[0], nil 77 } 78 default: 79 return nil, fmt.Errorf("not support output format: %s", command.format) 80 } 81 } 82 */