How to implement adaptive structure matching of imported xlsx files in Golang

299 views Asked by At

I have a requirement, it needs to import xlsx file to bulk insert objects into database.
Now, I am able to insert via pseudocode like below

import (
    "github.com/xuri/excelize/v2"
)
file, _, err := c.Request.FormFile("file")
if err != nil {
    return
}
xlsx, err := excelize.OpenReader(f)
if err != nil {
    return err
}
defer func() {
    if err := xlsx.Close(); err != nil {
        log.L(c).Info(err.Error())
    }
}()
rows, err := xlsx.GetRows(xlsx.GetSheetName(xlsx.GetActiveSheetIndex()))
if err != nil {
    fmt.Println(err)
    return nil, err
}
type TestObj struct{
    Test0 string   gorm:"column:test0" // Required fields
    Test1 string   gorm:"column:test1" // Required fields
    Test2 string   gorm:"column:test2" // Optional
    Test3 string   gorm:"column:test3" // Optional
    Test4 string   gorm:"column:test4" // Optional
}
objs := []TestObj{}
for i, row := range rows {
    if i == 0{     // 
        continue
    }
    var data TestObj
    for k, colCell := range row {
        if k==0{
            data.Test0=colCell 
        }
        if k==1{
            data.Test1=colCell 
        }
        if k==2{
            data.Test2=colCell 
        }
        if k==3{
            data.Test3=colCell 
        }
        if k==4{
            data.Test4=colCell 
        }
    }
    objs= append(objs, data)
}

service.BatchInsert(c,objs)

The way of the above code limits the flexibility of inserting data, for example, there are three options for Test2, Test3, and Test4.
Some uploaded forms may only contain some optional attributes. For example, the excel file contains Test1, Test0, Test4, and Test3, an error occurs when reading.

Is there some way to code that supports multiple upload file formats, such as Test0、Test1,Test4,Test3, and Test1,Test0,Test2, etc.

I really appreciate any help with this.

0

There are 0 answers