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

WBOY
Release: 2024-02-05 22:45:08
forward
518 people have browsed it

在 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
Copy after login

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
}

Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template