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)
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM