go 读取excel数据存储到mysql
一、安装依赖
go get github.com/go-sql-driver/mysql
go get github.com/jmoiron/sqlx
二、main.go
package main
import (
"fmt"
"github.com/jmoiron/sqlx"
"log"
)
import "github.com/tealeg/xlsx"
import _ "github.com/go-sql-driver/mysql"
type Student struct {
Name string
Sex string
}
func (student Student) show() {
fmt.Printf("Name:%s Sex:%s\r\n", student.Name, student.Sex)
}
func main() {
excelPath := "students.xlsx"
xlFile, err := xlsx.OpenFile(excelPath)
if err != nil {
fmt.Printf("Error opening Excel file: %s\n", err)
return
}
sheet := xlFile.Sheets[0]
var students []Student
i := 0
for _, row := range sheet.Rows {
name := row.Cells[0].String()
sex := row.Cells[1].String()
fmt.Printf("name:%s sex:%s \r\n", name, sex)
students = append(students, Student{Name: name, Sex: sex})
i++
}
for _, student := range students {
student.show()
}
/*数据库操作*/
fmt.Println("数据库操作")
dsn := "root:123456@tcp(192.168.31.132:3306)/demo"
db, err := sqlx.Open("mysql", dsn)
if err != nil {
log.Fatal(err)
}
for i, student := range students {
if i == 0 {
continue
}
db.NamedExec("insert into students(Name,Sex) values(:name,:sex)", student)
}
var studentMaps []*Student
err = db.Select(&studentMaps, `select name,sex from students where name=?`, "张三")
if err != nil {
log.Fatal(err)
}
for _, student := range studentMaps {
student.show()
}
}