package gamelogic import ( "context" "fmt" "path/filepath" "time" excelize "github.com/xuri/excelize/v2" ) var cacheBuffer [][]string var excelFile *excelize.File type Statistics struct { betAmount int winOrLossAmount int betArea []int waterpool int } type StatisticsList struct { lists []Statistics lastLists []Statistics tableId int } func (sl *StatisticsList) initData(tableId int) { sl.lists = []Statistics{} sl.lastLists = []Statistics{} sl.tableId = tableId go sl.updateValue() } func (sl *StatisticsList) updateValue() { for { c, cancel := context.WithTimeout(context.Background(), 60*time.Second) select { case <-c.Done(): sl.lastLists = []Statistics{} sl.lastLists = append(sl.lastLists, sl.lists...) sl.lists = []Statistics{} sl.storeToExcel() sl.lastLists = []Statistics{} cancel() } } } func (sl *StatisticsList) storeToExcel() { if len(sl.lastLists) == 0 { return } for n := 0; n < len(sl.lastLists); n++ { str := []string{fmt.Sprintf("%d", sl.lastLists[n].betAmount), fmt.Sprintf("%d", sl.lastLists[n].winOrLossAmount), fmt.Sprintf("%v", sl.lastLists[n].betArea), fmt.Sprintf("%d", sl.lastLists[n].waterpool), } cacheBuffer = append(cacheBuffer, str) } sl.saveFile() } func (sl *StatisticsList) saveFile() { var err error sheetName := "Sheet1" dirName := "./" fileName := fmt.Sprintf("masharie_table%d.xlsx", sl.tableId) excelFile = excelize.NewFile() excelFile.NewSheet(sheetName) // 设置列宽 excelFile.SetColWidth(sheetName, "A", "A", 20) excelFile.SetColWidth(sheetName, "B", "B", 20) excelFile.SetColWidth(sheetName, "C", "C", 20) excelFile.SetColWidth(sheetName, "D", "D", 20) style, _ := excelFile.NewStyle(&excelize.Style{ Alignment: &excelize.Alignment{ Horizontal: "center", Vertical: "center", }, }) excelFile.SetCellStyle(sheetName, "A1", "D1", style) // 设置工作表的单元格值 excelFile.SetCellValue(sheetName, "A1", "下注金额") excelFile.SetCellValue(sheetName, "B1", "盈利金额") excelFile.SetCellValue(sheetName, "C1", "投注区域") excelFile.SetCellValue(sheetName, "D1", "当前水池") // 获取已有数据的行数 rows, err := excelFile.GetRows(sheetName) if err != nil { return } rowIndex := len(rows) for _, row := range cacheBuffer { for colIndex, col := range row { cellName, _ := excelize.CoordinatesToCellName(colIndex+1, rowIndex+1) excelFile.SetCellValue(sheetName, cellName, col) excelFile.SetCellStyle(sheetName, cellName, cellName, style) } rowIndex++ } excelFile.SaveAs(filepath.Join(dirName, fileName)) }