美文网首页
go操作Excel文件

go操作Excel文件

作者: 彳亍口巴 | 来源:发表于2022-04-18 23:36 被阅读0次
    package main
    
    import (
        "bufio"
        "fmt"
        "github.com/tealeg/xlsx/v3"
        "io"
        "os"
        "strings"
    )
    
    func main() {
        //file, err := os.Create("C:\\Users\\smallzhou\\Desktop\\aa.txt")
        //defer file.Close()
        //if err != nil {
        //  fmt.Println("err=", err)
        //  return
        //}
        //map1 := make(map[string]string)
        //map1["hehe"] = "haha"
        //map1["hehe2"] = "haha2"
        //enc := gob.NewEncoder(file)
        //for _, v := range map1 {
        //  gob.Register(v)
        //}
        //err = enc.Encode(&map1)
        //if err != nil {
        //  fmt.Println(err)
        //}
        //bufi22()
        //readXLSX()
        gen(buildMap())
    }
    
    func bufi22() {
        file, err := os.Open("F:\\762513\\Desktop\\a.txt")
        if err != nil {
            fmt.Println("open file failed! err:%+v", err)
            return
        }
        defer file.Close()
        reader := bufio.NewReader(file)
        for {
            line, err := reader.ReadString('\n')
            if err == io.EOF {
                if len(line) != 0 {
                    fmt.Println(line)
                }
                fmt.Println("文件读完了")
                break
            }
            if err != nil {
                fmt.Println("read file failed, err:", err)
                return
            }
            fmt.Print(line)
        }
    }
    
    func readXLSX() {
        filename := "F:\\762513\\Desktop\\c.xlsx"
        xlFile, err := xlsx.OpenFile(filename)
        if err != nil {
            fmt.Println(err.Error())
            return
        }
        // 遍历sheet页读取
        for _, sheet := range xlFile.Sheets {
            fmt.Println("sheet name: ", sheet.Name)
    
            output := [][]string{} // 多行多列,就是一个二维数组
            err = sheet.ForEachRow(func(r *xlsx.Row) error {
                cells := []string{} // 每行又是一个数组
                err := r.ForEachCell(func(c *xlsx.Cell) error {
                    cells = append(cells, c.Value)
                    return nil
                })
                if err != nil {
                    return err
                }
                //fmt.Println("cells:",cells)
                output = append(output, cells)
                return nil
            })
            if err != nil {
                fmt.Printf("sheet.ForEachRow err=%#v\n", err)
            }
            fmt.Printf("output===%#v\n", output)
            for _, v := range output {
                fmt.Printf("line=%#v\n", v)
            }
        }
        fmt.Println("\n\nimport success")
    }
    
    type ExportInfo struct {
        Uin      string
        Desc     string
        FieldKey string
    }
    
    type Data struct {
        Uin  int
        Name string
        Age  int
    }
    
    func buildMap() []Data {
        var d []Data
        for i := 0; i < 10; i++ {
            d = append(d, Data{
                Uin:  i,
                Name: fmt.Sprintf("%d", i*i),
                Age:  i + 100,
            })
        }
        return d
    }
    
    func gen(datas []Data) {
        //filePath := "F:\\762513\\Desktop\\"
        //dir := filePath[:strings.LastIndex(filePath, "\\")]
        ////初始化本地日志
        //if _, err := os.Stat(dir); os.IsNotExist(err) {
        //  err := os.MkdirAll(dir, os.ModePerm)
        //  if err != nil {
        //      return
        //  }
        //}
        file := xlsx.NewFile()
        sheet, err := file.AddSheet("sheetName.xlsx")
        if err != nil {
            return
        }
        // 标题行
        row := sheet.AddRow()
        row.SetHeightCM(0.5)
        cell := row.AddCell()
        cell.Value = "uin"
        cell = row.AddCell()
        cell.Value = "name"
        cell = row.AddCell()
        cell.Value = "age"
        for _, v := range datas {
            row = sheet.AddRow()
            e := make([]string, 0)
            e = append(e, fmt.Sprintf("%d", v.Uin), v.Name, fmt.Sprintf("%d", v.Age))
            fmt.Println(e)
            row.WriteSlice(&e, -1)
        }
        err = file.Save("a.xlsx")
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println("success")
    }
    
    // GenerateExcelFile 生成excel文件
    func GenerateExcelFile(relativePath, sheetName string, titles []ExportInfo,
        datas []map[string]string) (string, error) {
        filePath := ""
        dir := filePath[:strings.LastIndex(filePath, "/")]
        //初始化本地日志
        if _, err := os.Stat(dir); os.IsNotExist(err) {
            err := os.MkdirAll(dir, os.ModePerm)
            if err != nil {
                return "", fmt.Errorf("MkdirAll failed, path: %s, err: %v", dir, err)
            }
        }
        file := xlsx.NewFile()
        sheet, err := file.AddSheet(sheetName)
        if err != nil {
            return "", fmt.Errorf("call AddSheet failed, sheetName: %s, err: %v", sheetName, err)
        }
    
        // 标题行
        row := sheet.AddRow()
        row.SetHeightCM(0.5)
        for i := range titles {
            cell := row.AddCell()
            cell.Value = titles[i].Desc
        }
        // 数据行
        for j := range datas {
            row = sheet.AddRow()
            e := make([]string, 0, len(titles))
            for i := range titles {
                value := datas[j][titles[i].FieldKey]
                e = append(e, value)
            }
            row.WriteSlice(&e, -1)
        }
    
        err = file.Save(filePath)
        return relativePath, err
    }
    
    

    相关文章

      网友评论

          本文标题:go操作Excel文件

          本文链接:https://www.haomeiwen.com/subject/yupjertx.html