github.com/easysoft/zendata@v0.0.0-20240513203326-705bd5a7fd67/cmd/test/others/func/comm/excel.go (about) 1 package comm 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/360EntSecGroup-Skylar/excelize/v2" 8 fileUtils "github.com/easysoft/zendata/pkg/utils/file" 9 ) 10 11 func GetExcelTable(filePath, sheetName string) (records []map[string]interface{}) { 12 13 excel, err := excelize.OpenFile(filePath) 14 if err != nil { 15 fmt.Printf("fail to read file %s, error: %s", filePath, err.Error()) 16 return 17 } 18 19 fileName := fileUtils.GetFileName(filePath) 20 fileName = strings.TrimSuffix(fileName, "词库") 21 22 for _, sheet := range excel.GetSheetList() { 23 if sheetName != sheet { 24 continue 25 } 26 27 rows, _ := excel.GetRows(sheet) 28 if len(rows) == 0 { 29 continue 30 } 31 32 colMap := map[int]string{} 33 colCount := 0 34 for colIndex, colVal := range rows[0] { 35 colMap[colIndex] = strings.TrimSpace(colVal) 36 colCount++ 37 } 38 39 for rowIndex, row := range rows { 40 if rowIndex == 0 { // ignore header 41 continue 42 } 43 44 record := map[string]interface{}{} 45 46 for colIndex, col := range row { 47 if colIndex >= colCount { 48 break 49 } 50 51 colName := colMap[colIndex] 52 colVal := strings.TrimSpace(col) 53 record[colName] = colVal 54 } 55 56 records = append(records, record) 57 } 58 } 59 60 return 61 } 62 63 func GetExcelFirstSheet(filePath string) (sheetName string, rows [][]string) { 64 excel, err := excelize.OpenFile(filePath) 65 if err != nil { 66 fmt.Printf("fail to read file %s, error: %s", filePath, err.Error()) 67 return 68 } 69 70 sheetName = excel.GetSheetList()[0] 71 rows, err = excel.GetRows(sheetName) 72 73 if err != nil { 74 fmt.Println(err) 75 } 76 77 return 78 }