推荐一个excel 轮子-极简用法

Golang
349
0
0
2022-06-27

解决excel 数据问题

github地址: github.com/qax-os/excelize/tree/ma...

实例

  1. 安装
go get github.com/xuri/excelize/v2
  1. 简单用法 写入数据到excel,支持多行 sheet
package main

import (
    "fmt"

    "github.com/xuri/excelize/v2"
)

func main() {
    f := excelize.NewFile()
    // Create a new sheet.
    index := f.NewSheet("Sheet2")
    // Set value of a cell.
    f.SetCellValue("Sheet2", "A2", "Hello world.")
    f.SetCellValue("Sheet1", "B2", 100)
    // Set active sheet of the workbook.
    f.SetActiveSheet(index)
    // Save spreadsheet by the given path. 
    if err := f.SaveAs("Book1.xlsx"); err != nil {
        fmt.Println(err)
    }
}
  1. 读取excel
package main

import (
    "fmt"

    "github.com/xuri/excelize/v2"
)

func main() {
    f, err := excelize.OpenFile("Book1.xlsx")
    if err != nil {
        fmt.Println(err)
        return
    }
    // Get value from cell by given worksheet name and axis.
    cell, err := f.GetCellValue("Sheet1", "B2")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(cell)
    // Get all the rows in the Sheet1.
    rows, err := f.GetRows("Sheet1")
    if err != nil {
        fmt.Println(err)
        return
    }
    for _, row := range rows {
        for _, colCell := range row {
            fmt.Print(colCell, "\t")
        }
        fmt.Println()
    }
}

批量的数据如何 批量呢?

给你们一个思路,嘿嘿嘿

转换excel 数据函数

func (this *ProjectPlanController) ExportToXLSXMedicineData(ctx *gin.Context,projectId int) ([][]string, error) {
    // 查询出 当前项目下 所有的药物
    MedicineModel := NewMedicineModel(util.GetDbObject(ctx))
    MedicineModel.ProjectId = projectId
    MedicineList,count := MedicineModel.GetList(1,1000)

    var datas [][]string

    if count > 0 {
        datas = append(datas, []string{"药物名称","药物类型", "给药方式", "药物简介"})
        for _, m := range MedicineList  {
            datas = append(datas, []string{m.MedicineName, m.MedicineType, m.TakeMethod, m.Desc})
        }
    }

    return datas, nil
}

再使用函数来进行写入文件

此处,保密,你自己玩哈哈哈哈