Export Excel in golang

532 views Asked by At

I create an excel template and export it using excelite golang, they open quietly on Linux, but on Windows and Mac, when opening, an error occurs "there is an error in part of the contents in the book.xlsx. Make a recovery attempt? If you trust the source from which the book was obtained, click the "YES" button".I use gin

func (r *Router) exportTCMs(ctx *gin.Context) {

    var err error
    defer func() { abortWithStatusJSON(ctx, err) }()

    f := excelize.NewFile()
    defer func() {
        err := f.Close()
        fmt.Println(err)
    }()

    err = r.service.TCM.AllGroupsReportTCM(ctx.Request.Context(), f)
    if err != nil {
        return
    }

    fName := url.QueryEscape(time.Now().Format("2006-01-02_15_04_05") + ".xlsx")
    f.Path = fName

    ctx.Writer.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    ctx.Writer.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+f.Path)
    ctx.Writer.Header().Set("Content-Transfer-Encoding", "binary")

    if err := f.Write(ctx.Writer); err != nil {
        errors.New(http.StatusBadRequest, err.Error())
        return
    }
    //
    ctx.JSON(http.StatusOK, model.ResponseNoContent{Data: model.Empty{}, Message: ""})

}

I tried to change the headers, but nothing helps, I don't even know what the problem might be.

1

There are 1 answers

1
xuri On

Which version of the Go language and Excelize library are you using? Note that, there are some incompatible changes in the Go 1.21.0, the Excelize library can not working with that version normally, if you are using the Go 1.21.x, please upgrade to the Go 1.21.1 and later version.