本测试中使用的第三方库为:https://github.com/tealeg/xlsx ,其项目页上介绍“ ”Google Go (golang) library for reading and writing XLSX files. You should probably also checkout: https://github.com/360EntSecGroup-Skylar/excelize “ ,所以也可以引入https://github.com/360EntSecGroup-Skylar/excelize模块进行excel处理,不过其相较于python的模块来说,功能上还是比较弱。
一、读文件
go get github.com/tealeg/xlsx
先安装依赖库。读取的源文件内容如下:
读取文件的源代码如下:
package main
import(
"fmt"
"github.com/tealeg/xlsx"
)
var (
inFile = "test.xlsx"
)
func main(){
// 打开文件
xlFile, err := xlsx.OpenFile(inFile)
if err != nil {
fmt.Println(err.Error())
return
}
// 遍历sheet页读取
for _, sheet := range xlFile.Sheets {
fmt.Println("sheet name: ", sheet.Name)
//遍历行读取
for _, row := range sheet.Rows {
// 遍历每行的列读取
for _, cell := range row.Cells {
text := cell.String()
fmt.Printf("%20s", text)
}
fmt.Print("\n")
}
}
fmt.Println("\n\nimport success")
}
执行结果如下:
[root@localhost test]# go run rexcel.go
sheet name: Sheet1
site age email
www.361way.com 10 itybku@139.com
import success
二、写文件
代码如下:
package main
import(
"strconv"
"fmt"
"github.com/tealeg/xlsx"
)
var (
outFile = "/tmp/out_student.xlsx"
)
type Student struct{
Name string
age int
Phone string
Gender string
Mail string
}
func main(){
file := xlsx.NewFile()
sheet, err := file.AddSheet("student_list")
if err != nil {
fmt.Printf(err.Error())
}
stus := getStudents()
//add data
for _, stu := range stus{
row := sheet.AddRow()
nameCell := row.AddCell()
nameCell.Value = stu.Name
ageCell := row.AddCell()
ageCell.Value = strconv.Itoa(stu.age)
phoneCell := row.AddCell()
phoneCell.Value = stu.Phone
genderCell := row.AddCell()
genderCell.Value = stu.Gender
mailCell := row.AddCell()
mailCell.Value = stu.Mail
}
err = file.Save(outFile)
if err != nil {
fmt.Printf(err.Error())
}
fmt.Println("\n\nexport success")
}
func getStudents()[]Student{
students := make([]Student, 0)
for i := 0; i < 10; i++{
stu := Student{}
stu.Name = "name" + strconv.Itoa(i + 1)
stu.Mail = stu.Name + "@chairis.cn"
stu.Phone = "1380013800" + strconv.Itoa(i)
stu.age = 20
stu.Gender = "男"
students = append(students, stu)
}
return students
}
代码执行结果如下: