This is a creation in Article, where the information may have evolved or changed.
If the original data is in TXT, the format is as follows:
1.23 486 89.001
456.2 8.25 96.01
456.01 456.6 456.1
The number of spaces in each row is different, but the number is the same and the number of columns remains the same. You want to keep this data in the same number of rows and columns that you saved in Excel.
Saved in Excel, in the following format:
Col1 col2 col3
Row1 1.23 486 89.001
Row2 456.2 8.25 96.01
ROW3 456.01 456.6 465.1
The Golang code is as follows:
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")//write UTF-8 BOM
W: = csv. Newwriter (f)
SLI: = Getrowssli (str)//sli:[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 in line break is "\ n"
Func Getrowssli (str string) []string {
SLI: = Strings. Split (str, "\ n")
return SLI
}
32-> Space 9->tab
Func formatString (str string) []string {
Srclength: = Len (str)
Rtnsli: = []string{}
I: = 0
for {
If Str[i] >= && Str[i] <= 57 {
Start Loop data fetching
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
}