Go语言学习之-带分割符的文件转excel

package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"github.com/axgle/mahonia"
	"github.com/xuri/excelize/v2"
	"log"
	"os"
	"path"
	"path/filepath"
	"strings"
)

var splitor = ""
func splt(c rune) bool {
	//c = ''
	if c == rune(splitor[0]) {
		return true
	} else {
		return false
	}
}

func ToAlphaString(value int) string {
	if value < 0 {
		return ""
	}
	var ans string
	i := value + 1
	for i > 0 {
		ans = string((i-1)%26+65) + ans
		i = (i - 1) / 26
	}
	return ans
}

func main() {
	var enc mahonia.Decoder
	enc = mahonia.NewDecoder("gbk")
	//filename := "C:\\Users\\Downloads\\111.del"
	var filename string
	if len(os.Args)>1{
		flag.ErrHelp=errors.New("")
		flag.StringVar(&filename,"filename","111.dat","--filename 文件名【可以把文件拖放在此处】")
		flag.StringVar(&splitor,"splitor","\u0003","--splitor [,  \u0008 \u0003  ]  分割符,一般为\u0003或者逗号等可见字符单字符")
		flag.Parse()
		//rune(splitor)
		fmt.Println("filename:"+filename)
		//fmt.Println([]rune(splitor))
		fmt.Println("splitor:"+string(splitor))
		//return
	}else{
		fmt.Println("请输入文件名,可以直接把用鼠标点击文件拖入到此:")
		fmt.Scan(&filename)
	}


	if len(filename)<5{
		tmpstr:=fmt.Sprintf("输入的文件名[%s]长度好像不够5位,是否有问题?",filename)
		panic(errors.New(tmpstr))
	}
	paths,basefile:=filepath.Split(filename)
	filesuffix:=path.Ext(basefile)
	newbasename:=paths+basefile[0:len(basefile) - len(filesuffix)]
	xlsfilename:=newbasename+".xlsx"
	logfilename:=newbasename+".log"

	logFile,err:=os.OpenFile(logfilename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		fmt.Println("open log file failed, err:", err)
		return
	}
	log.SetOutput(logFile)
	log.SetFlags(log.Lshortfile | log.Lmicroseconds | log.Ldate)
	log.Printf("日志文件:[%s]\n",logfilename)
	log.Printf("目标文件[%s]\n",xlsfilename)
	fmt.Printf("目标文件路径为:[%s]\n",xlsfilename)
	fmt.Printf("目标日志路径为:[%s]\n",logfilename)
	fp1, err := os.Open(filename)
	if err != nil {
		tmpstr := fmt.Sprintf("%s文件打开错误!", filename)
		log.Println(tmpstr)
		panic(err)
	}
	defer fp1.Close()

	fs := bufio.NewScanner(fp1)
	var rowno = 2
	//xlsfilename := "1122221.xlsx"
	f := excelize.NewFile()
	f.SaveAs(xlsfilename)
	file1, err := excelize.OpenFile(xlsfilename)
	if err != nil {
		log.Println(err)
	}

	streamWriter,err:=file1.NewStreamWriter("Sheet1")
	if err != nil {
		log.Println(err)
	}

	defer func() {
		if err := recover();err!=nil{
			streamWriter.Flush()
			f.SaveAs(xlsfilename)
			file1.Save()
			log.Printf("recover:%v",err)
		}
	}()

	//defer f.SaveAs(xlsfilename)
	//index:=f.NewSheet("data")
	//f.SetActiveSheet(index)
	for fs.Scan() {
		splitstrLine := fs.Text()
		//fildstr := strings.FieldsFunc(splitstrLine, splt)
		fildstr := strings.Split(splitstrLine, splitor)
		//log.Printf("fildstr:%v",fildstr)
		colcnt:=len(fildstr)
		//log.Printf("pos:%d-->colcnt:[%d]\n",rowno,colcnt)
		row:=make([]interface{},colcnt)
		for colno := 0; colno < colcnt; colno++ {
			if fildstr[colno]!="" {
				row[colno]=enc.ConvertString(fildstr[colno])
			}else {
				row[colno]=""
			}
		}
		cell,_:=excelize.CoordinatesToCellName(1,rowno)
		if err:=streamWriter.SetRow(cell,row);err!=nil{
			log.Println(err)
		}
		if rowno%30000 == 0 {
			log.Printf("-----已写入[%d]行------\n", rowno)
		}

		if rowno > excelize.TotalRows{
			panic(errors.New("rows number exceeds maximum limit"))
		}


		//if rowno >= 20000 {
		//	break
		//}

		rowno++
	}
	if err:=streamWriter.Flush();err!=nil{
		log.Println(err)
		//return
	}

	if err:=file1.Save();err!=nil{
		log.Println(err)
	}
	//println(fp1)
	log.Println("完成!")
	os.Exit(0)
}
posted @ 2021-09-23 14:28  silencemaker1221  阅读(125)  评论(0编辑  收藏  举报