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的方式写入,如果数据量小,直接写入即可.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | //读取并存入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) } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!