先下载第三方依赖包:
go get -u github.com/xuri/excelize/v2
假设原数据格式为:
type Data struct { Psa string Group string Operator string }
将数据插入新生成的execl表格中,并且当group值相同时,只更新该group的operator值,即最终数据中,group没有相同值
package main import ( "fmt" "github.com/xuri/excelize/v2" ) type Data struct { Psa string Group string Operator string } func generateExcel(data []Data) error { // 创建一个新的 Excel 文件 f := excelize.NewFile() // 将第一个工作表的名称定为"sheet" sheet := f.GetSheetName(0) // 设置表头 f.SetCellValue(sheet, "A1", "Psa") f.SetCellValue(sheet, "B1", "Group") f.SetCellValue(sheet, "C1", "Operator") // 创建一个map,key 类型为 string (对应 group 字段),value 类型为 int (对应 Excel 表格中的行号) groupOperatorMap := make(map[string]int) // 设置行数,从2开始,因为第一行是表头 i := 2 // 遍历原数据 for _, value := range data { //判断当前 group 是否已经存在于 groupOperatorMap 中,并将 group 对应的行号存储在 idx 变量中 if idx, ok := groupOperatorMap[value.Group]; ok { f.SetCellValue(sheet, fmt.Sprintf("C%d", idx), value.Operator) //如果存在,则更新对应行的 Operator 值 } else { //如果不存在,则插入新行 f.SetCellValue(sheet, fmt.Sprintf("A%d", i), value.Psa) //fmt.Sprintf("A%d", i) 根据i值生成excel单元格的值,如"A2" f.SetCellValue(sheet, fmt.Sprintf("B%d", i), value.Group) f.SetCellValue(sheet, fmt.Sprintf("C%d", i), value.Operator) //将当前 group 和对应的行号存储到 groupOperatorMap 中,并将行号递增 groupOperatorMap[value.Group] = i i++ } } // 保存 Excel 文件,默认存储当前目录下 return f.SaveAs("output.xlsx") } func main() { data := []Data{ {Psa: "psa1", Group: "group1", Operator: "operator1"}, {Psa: "psa2", Group: "group2", Operator: "operator2"}, {Psa: "psa3", Group: "group3", Operator: "operator3"}, {Psa: "psa1", Group: "group1", Operator: "operator4"}, {Psa: "psa1", Group: "group4", Operator: "operator5"}, {Psa: "psa2", Group: "group2", Operator: "operator6"}, } err := generateExcel(data) if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Excel file generated successfully.") } }
结果展示:
标签:Group,string,--,fmt,Psa,excel,Operator,Go,sheet From: https://www.cnblogs.com/Xinenhui/p/18220266