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 44 45 46 47 48 49
| type ExcelHelper struct { FileName string Header []string SheetNameWithData map[string][]any }
func (e *ExcelHelper) GenerateExcelWithSheets() error { file := excelize.NewFile() var ints []int for sheetName, data := range e.SheetNameWithData { file.NewSheet(sheetName) file.DeleteSheet("Sheet1") for i := 0; i < len(e.Header); i++ { k := 'A' + i file.SetCellValue(sheetName, string(rune(k))+"1", e.Header[i]) file.SetColWidth(sheetName, "A", "A", 45) file.SetColWidth(sheetName, "B", "B", 70) file.SetColWidth(sheetName, "C", "C", 45) } for i := 0; i < len(data); i++ { row := i + 2 a := data[i] t := reflect.ValueOf(a) if t.Kind() == reflect.Ptr { t = t.Elem() } for j := 0; j < t.NumField(); j++ { field := t.Field(j) k := 'A' + j file.SetCellValue(sheetName, string(rune(k))+strconv.Itoa(row), field.Interface()) log.Println("写入sheet: " + sheetName + " 行索引: " + strconv.Itoa(row) + " 列索引: " + string(rune(k)) + " 值: " + field.String()) } } log.Println("sheet " + sheetName + " 写入成功") ints = append(ints, 1) } err := file.SaveAs(e.FileName) if err != nil { fmt.Println("save excel fail " + err.Error()) return err } return nil }
func NewExcelHelper(fileName string, header []string, SheetNameWithData map[string][]any) *ExcelHelper { return &ExcelHelper{FileName: fileName, Header: header, SheetNameWithData: SheetNameWithData} }
|