I am trying to combine data from multiple cells from an excel spreadsheet into one JSON encoded string. I cannot figure out how to do so, the code below is creating a new JSON object per cell. How do I differentiate the cells to combine into the same JSON string?
package main
import (
"fmt"
"github.com/tealeg/xlsx"
"encoding/json"
)
func main() {
excelFileName := "/Users/isaacmelton/Desktop/Test_Data.xlsx"
xlFile, err := xlsx.OpenFile(excelFileName)
if err != nil {
fmt.Printf("Cannot parse data")
}
for _, sheet := range xlFile.Sheets {
for _, row := range sheet.Rows {
fmt.Printf("
")
for x, cell := range row.Cells {
if x == 3 || x == 5 {
data := map[string]string{"d_name": cell.String(), "name": cell.String()}
json_data, _ := json.Marshal(data)
fmt.Println(string(json_data))
}
}
}
}
}
Running the above code results in the following:
{"foo":"cell1","bar":"cell1"}
{"foo":"cell2","bar":"cell2"}
I expect something like this:
{"foo":"cell1", "bar":"cell2"}
If I right understand your request you just need to define root element, add cells into it and marshal this element rather than individual cells.
root := []map[string]string{}
for x, cell := range row.Cells {
if x == 3 || x == 5 {
root = append(root, map[string]string{"d_name": cell.String(), "name": cell.String()})
}
}
json_data, _ := json.Marshal(root)
fmt.Println(string(json_data))
You may use
a, err := row.Cells[3].String()
b, err := row.Cells[5].String()
Like this working code:
package main
import (
"encoding/json"
"fmt"
"github.com/tealeg/xlsx"
)
func main() {
xlFile, err := xlsx.OpenFile(`Test_Data.xlsx`)
if err != nil {
panic(err)
}
for _, sheet := range xlFile.Sheets {
for _, row := range sheet.Rows {
//for x, cell := range row.Cells {
//if x == 3 || x == 5 {
a, err := row.Cells[3].String()
if err != nil {
panic(err)
}
b, err := row.Cells[5].String()
if err != nil {
panic(err)
}
data := map[string]string{"d_name": a, "name": b}
json_data, err := json.Marshal(data)
if err != nil {
panic(err)
}
fmt.Println(string(json_data))
//}
//}
}
}
}
output:
{"d_name":"1000","name":"a"}
{"d_name":"2000","name":"b"}
{"d_name":"3000","name":"c"}
{"d_name":"4000","name":"d"}
{"d_name":"5000","name":"e"}
input file content:
1 10 100 1000 10000 a
2 20 200 2000 20000 b
3 30 300 3000 30000 c
4 40 400 4000 40000 d
5 50 500 5000 50000 e