golang steam create/download xls

2018-11-12  本文已影响0人  pandanrain
package main
import (
  "fmt"
  "log"
  "net/http"
  "github.com/tealeg/xlsx"
)

func main() {
    oexcel := func(w http.ResponseWriter, req *http.Request) {
        _, err := xlsx.OpenFile("/tmp/test.xlsx") // here open you local file path
       if err != nil {
            fmt.Println(err)
            return
        }

        fmt.Println("no err")
    }

    dexcel := func(w http.ResponseWriter, req *http.Request) {
        headers := []string{"groupName", "groupID", "groupPath", "groupOwner"}
        filename := "test"

        w.Header().Add("Content-Disposition", "attachment;filename=\""+filename+".xlsx\"")
        w.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8")
        w.Header().Set("X-Content-Type-Options", "nosniff")
        b := xlsx.NewStreamFileBuilder(w)
        cellType := xlsx.CellTypeString

        ct := []*xlsx.CellType{cellType.Ptr(), cellType.Ptr(), cellType.Ptr(), cellType.Ptr()}

        if err := b.AddSheet("Sheet1", headers, ct); err != nil {
            fmt.Println("end")
            return
        }
        sf, err := b.Build()
        if err != nil {
            fmt.Println("end")
            return
        }
        defer sf.Close()
        for i := 0; i < 100; i++ {
            sf.Write([]string{"GroupName", "GroupID", "PathName", "OwnerAccount"})
            sf.Flush()
        }
        return
     }
    http.HandleFunc("/openExcel", oexcel)
    http.HandleFunc("/downloadExcel", dexcel)
    log.Fatal(http.ListenAndServe(":8080", nil))
}
5169B083-7ECC-4AAD-B750-87FA3E7795C4.png

解决办法来源:https://github.com/tealeg/xlsx/issues/365

Quick fix:
in stream_file_builder.go line 52 change
initMaxStyleId = 1
to
initMaxStyleId = 0
上一篇下一篇

猜你喜欢

热点阅读