go合并Excel文件

  • 之前写的一个go合并excel小demo
  • 编译之后 放入要合并的excel目录 执行 集合自动遍历Excel文件将所有合并生成一个新文件
  • 代码
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)
	}

}