go合并Excel文件

  • 之前写的一个go合并excel小demo
  • 编译之后 放入要合并的excel目录 执行 集合自动遍历Excel文件将所有合并生成一个新文件
  • 代码
    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
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    package main

    import (
    "strings"
    "path/filepath"
    "os"
    "github.com/tealeg/xlsx"
    "fmt"
    "time"
    "errors"
    "log"
    "runtime"
    "flag"
    //"os/exec"
    "path"
    )

    type outputer func(s string)
    var fileName = "merge" + time.Now().String()
    var dir string

    //var xlsxPath = flag.String("f", "", "Path to an XLSX file")
    //var sheetIndex = flag.Int("i", 0, "Index of sheet to convert, zero based")
    var inputDir = flag.String("d", "", "选择需要合并文件路径 ; 默认 : 当前程序运行时目录")
    var putOutDir = flag.String("p", "", "选择输出目录 ; 默认 : User/Documents/mergeExcel")
    var help = flag.String("h","", "for help")



    /**
    * 读取目录文件
    */
    func WalkDir(dirPth, suffix string) (files []string, err error) {
    files = make([]string, 0, 30)
    suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写

    err = filepath.Walk(dirPth, func(filename string, fi os.FileInfo, err error) error { //遍历目录
    //if err != nil { //忽略错误
    // return err
    //}

    if fi.IsDir() { // 忽略目录
    return nil
    }

    if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) {
    files = append(files, filename)
    }

    return nil
    })

    return files, err
    }

    /**
    * 合并excel
    */
    func mergeExcel(excelFileName []string, sheetIndex int, outputf outputer) error {
    new_file := xlsx.NewFile()
    new_sheet, err := new_file.AddSheet("Sheet1")

    for k,v := range excelFileName{
    log.Println("当前进度:",k+1,"/",len(excelFileName)," 文件名:",path.Base(v))
    xlFile, error := xlsx.OpenFile(v)

    if error != nil {
    return error
    }
    sheetLen := len(xlFile.Sheets)
    switch {
    case sheetLen == 0:
    return errors.New("This XLSX file contains no sheets.")
    case sheetIndex >= sheetLen:
    return fmt.Errorf("No sheet %d available, please select a sheet between 0 and %d\n", sheetIndex, sheetLen-1)
    }
    sheet := xlFile.Sheets[sheetIndex]

    if err != nil{
    panic(err)
    }
    for rowK, row := range sheet.Rows {
    //从第二个文件开始忽略标题
    if k > 0 && rowK == 0{
    continue
    }
    new_row := new_sheet.AddRow()
    //var vals []string
    if row != nil {
    for _, cell := range row.Cells {
    //fmt.Println("文件:",k+1,"行数:",rowK,"列数:",cell_k)
    new_cell := new_row.AddCell()
    str, err := cell.String()
    if err != nil {
    //vals = append(vals, err.Error())
    }
    new_cell.Value = str
    //vals = append(vals, fmt.Sprintf("%q", str))
    }
    //outputf(strings.Join(vals, *delimiter) + "\n")


    }
    }
    err := new_file.Save(dir +"/" + fileName + ".xlsx")
    if err != nil {
    panic(err)
    }
    }
    log.Println("文件合并成功. 文件名:",dir +"/" + fileName +".xlsx")
    return nil
    }

    func getCurrentDirectory() string {
    dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
    if err != nil {
    log.Fatal(err)
    }
    return strings.Replace(dir, "\\", "/", -1)
    }

    func main() {


    //var getName map[int]string
    //var getValue string

    // 解析
    //flag.Parse()
    //
    //
    ////// visit只包含已经设置了的flag
    //fmt.Println("------ visit flag start ------")
    //flag.Visit(func(f *flag.Flag) {
    // getName := f.Name
    // fmt.Println(getName)
    // //getValue := f.Value
    //})
    ////fmt.Println(getName)
    //fmt.Println("------ visit flag end ------")
    //
    //file, _ := exec.LookPath(os.Args[0])
    //dir, _ := filepath.Abs(file)
    dir = getCurrentDirectory()
    log.Println("当前目录",dir)
    //////////


    //flag.Parse()
    //
    //if len(os.Args) < 3 {
    // flag.PrintDefaults()
    // return
    //}


    //return

    runtime.GOMAXPROCS(runtime.NumCPU())
    printer := func(s string) { fmt.Printf("%s", s) }
    files, err := WalkDir(dir, ".xlsx")
    //fmt.Println(files)
    if err != nil {
    panic(err)
    }
    //memgeExcel(files, 0 , printer)
    if err := mergeExcel(files, 0 , printer); err != nil {
    fmt.Println(err)
    }

    }