Golang 第三方庫學習 · xlsx

weixin_34402408發表於2018-03-02

本文為轉載,原文:Golang 第三方庫學習 · xlsx

4822713-0464f13ee77ea44b.png
Golang

介紹

xlsx 是對新版本的Excel進行簡單讀寫操作的golang第三方庫,支援的檔案格式是.xlsx

原始碼

第三方庫原始碼:
https://github.com/tealeg/xlsx
本文原始碼:
https://github.com/Chain-Zhang/third-lib

安裝

go get github.com/tealeg/xlsx

使用

Read

excel 檔案內容:

4822713-b306e1f999550d9c..png
excel資料

讀取excel檔案程式碼:

import(
    "fmt"
    "github.com/tealeg/xlsx"
)

var (
    inFile = "/Users/chain/Downloads/student1.xlsx"
)

func Import(){
    // 開啟檔案
    xlFile, err := xlsx.OpenFile(inFile)
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    // 遍歷sheet頁讀取
    for _, sheet := range xlFile.Sheets {
        fmt.Println("sheet name: ", sheet.Name)
        //遍歷行讀取
        for _, row := range sheet.Rows {
            // 遍歷每行的列讀取
            for _, cell := range row.Cells {
                text := cell.String()
                fmt.Printf("%20s", text)
            }
            fmt.Print("\n")
        }
    }
    fmt.Println("\n\nimport success")
}

測試程式碼:

import(
    "testing"
)

func TestImport(t *testing.T){
    Import()
}

結果:

4822713-aad11fd150bf1e92..png
匯入結果

Write

import(
    "strconv"
    "fmt"
    "github.com/tealeg/xlsx"
)

var (
    inFile = "/Users/chain/Downloads/student1.xlsx"
    outFile = "/Users/chain/Downloads/out_student.xlsx"
)

type Student struct{
    Name string
    age int
    Phone string
    Gender string
    Mail string
}

func Export(){
    file := xlsx.NewFile()
    sheet, err := file.AddSheet("student_list")
    if err != nil {
        fmt.Printf(err.Error())
    }
    stus := getStudents()
    //add data
    for _, stu := range stus{
        row := sheet.AddRow()
        nameCell := row.AddCell()
        nameCell.Value = stu.Name

        ageCell := row.AddCell()
        ageCell.Value = strconv.Itoa(stu.age)

        phoneCell := row.AddCell()
        phoneCell.Value = stu.Phone

        genderCell := row.AddCell()
        genderCell.Value = stu.Gender

        mailCell := row.AddCell()
        mailCell.Value = stu.Mail
    }
    err = file.Save(outFile)
    if err != nil {
        fmt.Printf(err.Error())
    }
    fmt.Println("\n\nexport success")
}

func getStudents()[]Student{
    students := make([]Student, 0)
    for i := 0; i < 10; i++{
        stu := Student{}
        stu.Name = "name" + strconv.Itoa(i + 1)
        stu.Mail = stu.Name + "@chairis.cn"
        stu.Phone = "1380013800" + strconv.Itoa(i)
        stu.age = 20
        stu.Gender = "男"
        students = append(students, stu)
    }
    return students
}

測試程式碼:

import(
    "testing"
)

func TestExport(t *testing.T){
    Export()
}

匯出結果:

4822713-3608f5b9fd3924b6..png
匯出結果

轉載請註明出處
Golang 第三方庫學習 · xlsx

相關文章