How do I add columns to an existing excel worksheet using golang and excelize?

Issue

I have some go code that opens a spreadsheet and for each row, uses a lanid in the row to lookup some data. I would like to add this derived data as two new columns in the sheet.

Opening the sheet and looping over all the rows works fine. I just can’t figure out how to add the new columns. Any suggestions welcome.

The code below throws an error of

panic: runtime error: index out of range [7] with length 7

like the columns haven’t been added.

f, e := excelize.OpenFile("apps.xlsx")
if e != nil {
    log.Fatal(err)
}

defer func() {
    if err := f.Close(); err != nil {
        fmt.Println(err)
    }
}()

f.InsertCol("apps", "H")
f.InsertCol("apps", "H")

rows, err := f.GetRows("apps")
if err != nil {
    fmt.Println(err)
    return
}
for _, row := range rows {
    lanid := row[3]
    
    fmt.Print(lanid, "\t")
    fmt.Println()
    node := orgtee.lookup(lanid)
    row[7] = node.title
    row[8] = node.domain
}

Solution

You can set it by SetCellValue function.

This is the example.

    for i := 1; i < len(rows); i++ {
        f.SetCellValue("apps", "G"+strconv.Itoa(i), "coba1")
        f.SetCellValue("apps", "H"+strconv.Itoa(i), "coba2")
        f.SetCellValue("apps", "I"+strconv.Itoa(i), "coba3")
    }

    rows, err = f.GetRows("apps") // call GetRows again to update rows value
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(rows)

Answered By – Rahmat Fathoni

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.