1.安装excelize
go get github.com/xuri/excelize/v2
2.代码
package main
import (
"encoding/json"
"fmt"
"github.com/xuri/excelize/v2"
"os"
)
func main() {
//读取excel文件
f, err := excelize.OpenFile("999.xlsx")
if err != nil {
fmt.Println("错误:", err)
return
}
defer func() {
// Close the spreadsheet.
if err := f.Close(); err != nil {
fmt.Println("错误:", err)
}
}()
//读取Sheet1
rows, err := f.GetRows("Sheet1")
if err != nil {
fmt.Println("错误:", err)
return
}
rowLetter := map[int]string{1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "F", 7: "G", 8: "H", 9: "I", 10: "J", 11: "K", 12: "L", 13: "M", 14: "N", 15: "O", 16: "P", 17: "Q", 18: "R", 19: "S", 20: "T", 21: "U", 22: "V", 23: "W", 24: "X", 25: "Y", 26: "Z"}
var data = make(map[int]map[string]string)
var son map[string]string
for l, row := range rows {
son = make(map[string]string)
for k, colCell := range row {
column := "-"
k += 1
if k > 26 {
c := int(k / 26)
y := int(k % 26)
if y == 0 {
c = c - 1
y = 26
}
column = rowLetter[c] + rowLetter[y]
} else {
column = rowLetter[k]
}
son[column] = colCell
}
data[l] = son
}
datastr, _ := json.Marshal(data) //字典转json
//保存文件
file, err := os.OpenFile("excel.json", os.O_CREATE, 0)
if err != nil {
fmt.Println("错误:", err)
return
}
defer file.Close()
_, err = file.Write(datastr)
if err != nil {
fmt.Println("错误:", err)
return
}
fmt.Println("ok")
}