go操作excel

第三方包准备:

  go get -u github.com/xuri/excelize/v2

 

案例: 读取excel,去除空行,筛选第二列不为空的行并将最终结果存入新的excel中.

思路: 读取excel,使用GetRows()方法读取指定sheet中所有数据,如果excel数据量庞大,可以指定一个int类型的flag,通过GetCellValue()方法逐行读取,因为我只保存两列数据,所以保存在了map中,具体视情况设计结构.

    保存excel,先将表头写入第一行,通过遍历保存的map,分别将key和value写入第一列和第二列中,下边采用闭包和多goroutine的方式写入,如果数据量小,直接写入即可.

//读取并存入excel

func writeExcel(title []string, dataMap map[string]string) {
	var flag = make(chan bool, 100)
	newFile := excelize.NewFile()                      // 创建一个excel文件句柄
	_ = newFile.SetCellValue("Sheet1", "A1", title[0]) //写入表头
	_ = newFile.SetCellValue("Sheet1", "B1", title[1])
	line := 1
	for k, v := range dataMap {
		line++
		go func(line int, k, v string) { // 数据量小可以不使用goroutine
			_ = newFile.SetCellValue("Sheet1", "A"+strconv.Itoa(line), k)
			_ = newFile.SetCellValue("Sheet1", "B"+strconv.Itoa(line), v)
			flag <- true
		}(line, k, v)
		<-flag
	}
	_ = newFile.SaveAs("newFile.xlsx") //保存成excel
}

func main() {
	/*
		筛选出非空行,而且第二列不为空的数据
	*/
	file, err := excelize.OpenFile("测试.xlsx") //打开excel并生成句柄
	defer func() {
		_ = file.Close()
	}()
	if err != nil {
		panic(err)
	}
	codes, _ := file.GetRows("Sheet1") //读取整个Sheet1表,返回的是一个string类型的二维切片格式
	var title []string
	var dataMap = make(map[string]string)
	for index, row := range codes { //row即是每一行的数据
		if index == 0 {
			title = row[:2]
		} else if len(row) > 1 && row[1] != "" { //筛选数据不为空,并且第二列也不为空的行
			dataMap[row[0]] = row[1]
		}
	}
	writeExcel(title, dataMap)
}

  

 

posted @ 2022-01-13 11:08  屁桃  阅读(1399)  评论(0编辑  收藏  举报