go excel导入导出

作者: adm 分类: go 发布时间: 2022-03-18 10:37
import (
    "fmt"
    "github.com/tealeg/xlsx"
)
func GoodsExport(c *gin.Context) {
    var list []GoodsExports
    dbMysql := mysql.GetORM()
    sql := `select goods_id,user_id,goods_name from tb_goods`
    dbMysql.SQL(sql).Find(&list)
    //导出
    var file *xlsx.File
    var sheet *xlsx.Sheet
    var row *xlsx.Row
    var err error

    file = xlsx.NewFile()
    sheet, err = file.AddSheet("Sheet1")
    if err != nil {
        fmt.Printf(err.Error())
    }

    row = sheet.AddRow()
    row.AddCell().Value = "商品ID"
    row.AddCell().Value = "用户"
    row.AddCell().Value = "商品标题"
    for _, v := range list {
        row = sheet.AddRow()
        row.AddCell().Value = strconv.Itoa(v.GoodsId)
        row.AddCell().Value = v.UserId
        row.AddCell().Value = v.GoodsName
    }
    buf := new(bytes.Buffer)
    err = file.Write(buf)
    if err != nil {
        fmt.Printf(err.Error())
        return
    }
    c.Header("Content-Description", "File Transfer")
    c.Header("Content-Disposition", "attachment; filename=商品.xlsx")
    c.Data(http.StatusOK, "text/xlsx", buf.Bytes())

}

//导入
output, err := xlsx.FileToSlice("demo.xlsx")
	if err != nil {
		panic(err.Error())
	}
	log.Println(output[0][1][1])
	for rowIndex, row := range output[0] {
		for cellIndex, cell := range row {
			log.Println(fmt.Sprintf("第%d行,第%d个单元格:%s", rowIndex+1, cellIndex+1, cell))
		}
	}


如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!