雑多なブログ

音楽や語学、プログラム関連の話題について書いています

go: Excelのファイルのセルの値を読んでJSONで出力するサンプル

仕事で使う可能性があるので、Excelのセルを読んでJSONで出力する方法を調べた。実際はもっと複雑な構造のJSONを出力する必要性があるかもしれないので、 goに不慣れな自分は挫折しそうだけども・・・

サンプルExcelの内容

key value note
k_001 なす 野菜
k_002 クッキー お菓子
k_003 お皿 食器
k_004 液体
k_005 トマト 野菜

出力JSONのフォーマット

[
    {"id": "ID文字列", "name": "なまえ", "note": "備考"},
    {"id": "ID文字列", "name": "なまえ", "note": "備考"},
    ...
]

ソース

package main

import (
    "encoding/json"
    "fmt"
    "os"

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

type inventoryItem struct {
    ItemKey string `json:"id"`
    Value   string `json:"name"`
    Note    string `json:"note"`
}

type inventory []*inventoryItem

func main() {
    if len(os.Args) != 2 {
        fmt.Println("パスを指定してください。")
        return
    }

    path := os.Args[1]

    f, err := excelize.OpenFile(path)
    if err != nil {
        fmt.Println(err)
        return
    }

    rows, err := f.GetRows("sheet1")
    if err != nil {
        fmt.Println(err)
        return
    }

    var data inventory

    for index, row := range rows {
        if index < 2 {
            continue
        }
        data = append(data, &inventoryItem{
            ItemKey: row[0],
            Value:   row[1],
            Note:    row[2],
        })
    }

    str, _ := json.Marshal(data)
    fmt.Print(string(str))
}

実行結果

[{"id":"k_001","name":"なす","note":"野菜"},{"id":"k_002","name":"クッキー","note":"お菓子"},{"id":"k_003","name":"お皿","note":"食器"},{"id":"k_004","name":"水","note":"液体"},{"id":"k_005","name":"トマト","note":"野菜"}]