Home  >  Article  >  Backend Development  >  Convert Excel file data to JSON string in Go without any struct definition

Convert Excel file data to JSON string in Go without any struct definition

WBOY
WBOYforward
2024-02-05 22:45:08522browse

在 Go 中将 Excel 文件数据转换为 JSON 字符串,无需任何结构体定义

Question content

I am new to go language. I have a requirement where an application will read an excel file and convert it into a json string without relying on any defined structure. I explored a few libraries where either this structure definition is required or at least there must be excel column headers. For example,

github.com/xuri/excelize
github.com/onkarvhanumante/Excel2JsonTree
github.com/FerdinaKusumah/excel2json

However, I can't find anywhere that can handle raw excel data and convert it to json.

Please give me some guidance, thank you!


Correct answer


If you can treat all values ​​as strings, then you can do it as shown in the code snippet below. The script reads all worksheets (tabs) and creates json files in two formats (with and without headers).

package main

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

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

func main() {
    f, err := excelize.OpenFile("test.xlsx")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer func() {
        if err := f.Close(); err != nil {
            fmt.Println(err)
        }
    }()

    // could have multiple sheets
    sheets := f.GetSheetList()
    for _, sheetName := range sheets {
        d, err := f.GetRows(sheetName)
        if err != nil {
            fmt.Println("error reading sheet", sheetName, ":", err)
            return
        }

        saveAsJSON(d, sheetName+".json")
        saveAsJSONWithHeaders(d, sheetName+"_with_headers.json")
    }

}

func saveAsJSONWithHeaders(rows [][]string, filename string) error {
    data := make([]map[string]string, len(rows)-1)
    headers := rows[0]
    // excluding header row
    for i, row := range rows[1:] {
        data[i] = make(map[string]string)
        for j, cellValue := range row {
            data[i][headers[j]] = cellValue
        }
    }

    return saveAsJSON(data, filename)
}

func saveAsJSON(data interface{}, filename string) error {
    file, err := os.Create(filename)
    if err != nil {
        return err
    }
    defer file.Close()
    encoder := json.NewEncoder(file)
    if err := encoder.Encode(data); err != nil {
        return err
    }
    return nil
}

The above is the detailed content of Convert Excel file data to JSON string in Go without any struct definition. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete