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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
| package main import ( "fmt" "log"
"github.com/tealeg/xlsx/v3" ) func main() { xlFile, err := xlsx.OpenFile("input.xlsx") if err != nil { log.Fatalf("无法打开Excel文件: %v", err) } fmt.Println("这个表格中有", len(xlFile.Sheets), "个工作表:") for i, sh := range xlFile.Sheets { fmt.Println("输出工作表:", i, sh.Name) sh, ok := xlFile.Sheet[sh.Name] if !ok { fmt.Println("访问一个工作表失败") return } fmt.Println("这个工作表的最大行数:", sh.MaxRow)
allRowsData := make([][]string, 0)
err := sh.ForEachRow(func(row *xlsx.Row) error {
rowData := make([]string, 0)
fmt.Printf("行数据: %v\n | %v \n", rowData, len(rowData))
err := row.ForEachCell(func(cell *xlsx.Cell) error { text := cell.String() rowData = append(rowData, text) return nil })
if err != nil { return err }
allRowsData = append(allRowsData, rowData)
return nil }) if err != nil { log.Fatalf("遍历工作表时发生错误: %v", err) } for _, rowData := range allRowsData { fmt.Printf("行数据: %v\n", rowData) }
newFile := xlsx.NewFile()
newSheet, err := newFile.AddSheet("Sheet1") if err != nil { log.Fatalf("无法创建新工作表: %v", err) } chongfu := make([]int, 0) for i := 0; i < len(allRowsData)-1; i++ { containsInt(allRowsData[i+1:], allRowsData[i][3], allRowsData[i][6], &chongfu, i) } fmt.Println(chongfu) for index, rowData := range allRowsData { if !intExistsInSlice(index, chongfu) { row := newSheet.AddRow() for _, cellData := range rowData { cell := row.AddCell() cell.SetString(cellData) } } } err = newFile.Save("output.xlsx") if err != nil { log.Fatalf("无法保存新 Excel 文件: %v", err) } fmt.Println("已保存新的 Excel 文件:output.xlsx") } fmt.Println("exit...") }
func containsInt(slice [][]string, str1 string, str2 string, chongfu *[]int, i int) { for _, v := range slice { if v[3] == str1 && v[6] == str2 { fmt.Println("有重复:", str1, str2) *chongfu = append(*chongfu, i) } } }
func intExistsInSlice(target int, slice []int) bool { for _, v := range slice { if v == target { return true } } return false }
|