golang读写excel
本测试中使用的第三方库为: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的模块来说,功能上还是比较弱。
一、读文件
1go get github.com/tealeg/xlsx
先安装依赖库。读取的源文件内容如下:
读取文件的源代码如下:
1package main
2import(
3 "fmt"
4 "github.com/tealeg/xlsx"
5)
6var (
7 inFile = "test.xlsx"
8)
9func main(){
10 // 打开文件
11 xlFile, err := xlsx.OpenFile(inFile)
12 if err != nil {
13 fmt.Println(err.Error())
14 return
15 }
16 // 遍历sheet页读取
17 for _, sheet := range xlFile.Sheets {
18 fmt.Println("sheet name: ", sheet.Name)
19 //遍历行读取
20 for _, row := range sheet.Rows {
21 // 遍历每行的列读取
22 for _, cell := range row.Cells {
23 text := cell.String()
24 fmt.Printf("%20s", text)
25 }
26 fmt.Print("\n")
27 }
28 }
29 fmt.Println("\n\nimport success")
30}
执行结果如下:
1[root@localhost test]# go run rexcel.go
2sheet name: Sheet1
3 site age email
4 www.361way.com 10 [email protected]
5import success
二、写文件
代码如下:
1package main
2import(
3 "strconv"
4 "fmt"
5 "github.com/tealeg/xlsx"
6)
7var (
8 outFile = "/tmp/out_student.xlsx"
9)
10type Student struct{
11 Name string
12 age int
13 Phone string
14 Gender string
15 Mail string
16}
17func main(){
18 file := xlsx.NewFile()
19 sheet, err := file.AddSheet("student_list")
20 if err != nil {
21 fmt.Printf(err.Error())
22 }
23 stus := getStudents()
24 //add data
25 for _, stu := range stus{
26 row := sheet.AddRow()
27 nameCell := row.AddCell()
28 nameCell.Value = stu.Name
29 ageCell := row.AddCell()
30 ageCell.Value = strconv.Itoa(stu.age)
31 phoneCell := row.AddCell()
32 phoneCell.Value = stu.Phone
33 genderCell := row.AddCell()
34 genderCell.Value = stu.Gender
35 mailCell := row.AddCell()
36 mailCell.Value = stu.Mail
37 }
38 err = file.Save(outFile)
39 if err != nil {
40 fmt.Printf(err.Error())
41 }
42 fmt.Println("\n\nexport success")
43}
44func getStudents()[]Student{
45 students := make([]Student, 0)
46 for i := 0; i < 10; i++{
47 stu := Student{}
48 stu.Name = "name" + strconv.Itoa(i + 1)
49 stu.Mail = stu.Name + "@chairis.cn"
50 stu.Phone = "1380013800" + strconv.Itoa(i)
51 stu.age = 20
52 stu.Gender = "男"
53 students = append(students, stu)
54 }
55 return students
56}
代码执行结果如下:
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/golang-rw-xlsx/6068.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.