假如原始数据在txt中,格式如下:
1.23 486 89.001
456.2 8.25 96.01
456.01 456.6 456.1
每一行的空格数量不同,但是数字数量相同,列数保持一致。希望将这些数据保持所在行数和列数不变,保存在excel中。
保存在excel中,格式如下:
col1 col2 col3
row1 1.23 486 89.001
row2 456.2 8.25 96.01
row3 456.01 456.6 465.1
golang代码如下:
package main
import (
"encoding/csv"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
)
func main() {
dir := getCurrentFilePath()
readDir(dir)
fmt.Println("complete! press any key to close this window!")
var in string
fmt.Scanf("%s", &in)
}
func readDir(dir string) {
rd, err := ioutil.ReadDir(dir)
if err != nil {
fmt.Println("read dir error!")
return
}
for _, file := range rd {
filename := file.Name()
fmt.Println("filename: ", filename)
if strings.Contains(filename, ".txt") {
str := readfile(filename)
if str == "" {
fmt.Println("readfile error!!!!!!!")
return
}
xlsname := strings.Trim(filename, ".txt") + ".xls"
f, err := os.Create(xlsname)
if err != nil {
fmt.Println("create " + xlsname + "failed!!!!!")
}
defer f.Close()
f.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM
w := csv.NewWriter(f)
sli := getRowsSli(str) //sli:[ 12 45 8, 456 8 9,...]
for _, v := range sli {
val := formatString(v) //val: [12 45 8]
w.Write(val)
}
w.Flush()
}
}
}
func getCurrentFilePath() string {
file, _ := exec.LookPath(os.Args[0])
path, _ := filepath.Abs(file)
dir, _ := filepath.Split(path)
return dir
}
func readfile(filename string) string {
file, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Println("there is no source.txt")
return ""
}
f := string(file)
return f
}
//txt中换行是“\n”
func getRowsSli(str string) []string {
sli := strings.Split(str, "\n")
return sli
}
// 32->空格 9->tab
func formatString(str string) []string {
srcLength := len(str)
rtnSli := []string{}
i := 0
for {
if str[i] >= 48 && str[i] <= 57 {
// 开始循环取数据
var tmp string
for {
tmp = tmp + string(str[i])
i++
if i >= srcLength {
break
}
if str[i] == 32 || str[i] == 9 {
break
}
}
rtnSli = append(rtnSli, tmp)
}
if i >= srcLength {
break
}
i++
}
return rtnSli
}
有疑问加站长微信联系(非本文作者)