当前位置:网站首页>Use go language to read TXT file and write it into Excel
Use go language to read TXT file and write it into Excel
2022-07-05 07:27:00 【Humorous Jing Kejun】
package main
// usage:
// go mod init
// go mod tidy
// go env -w GO111MODULE=on
// go env -w GOPROXY=https://goproxy.cn,direct
// go get github.com/sirupsen/logrus
// go get github.com/xuri/excelize/v2
// go build
import (
"flag"
"fmt"
"github.com/sirupsen/logrus"
"github.com/xuri/excelize/v2"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"time"
)
func getData(filepath string) [][]string {
logrus.Info("this function is used to getData,filepath is -->>", filepath)
content, err := ioutil.ReadFile(filepath)
var target [][]string
if err != nil {
panic(err)
}
contentList := strings.Split(strings.TrimSpace(string(content)), "\r\n")
for _, val := range contentList {
target = append(target, strings.Split(val, " "))
}
return target
}
func writeData(f *excelize.File, sheetName string, number int, cellList [][]string) bool {
logrus.Info("this function is used to writeData")
for i, line := range cellList {
tmp := "B" + strconv.Itoa(i+number)
if err := f.SetSheetRow(sheetName, tmp, &line); err != nil {
logrus.Println(" Failed to write row cells ", err)
return false
}
}
return true
}
func getFilePath() (dirname, filepath string) {
/* Define variables to receive console parameters */
Folder name
//var dirname string
//
file name
//var path string
flag.StringVar(&dirname, "d", "", " The name of the folder where the file is stored The default is empty. ")
flag.StringVar(&filepath, "f", "", " File list names written in a specific order , The default is empty. ")
flag.Parse()
return dirname, filepath
}
func main() {
var filePathList []string
sheetName := "Sheet1"
if dirname, filepath := getFilePath(); dirname == "" && filepath == "" {
logrus.Info(" perform ./main -h Check usage ")
os.Exit(-1)
} else {
if dirname != "" {
logrus.Info("dirname Not empty ")
// Get information about files or directories
fileInfoList, err := ioutil.ReadDir(dirname)
if err != nil {
log.Fatal(err)
}
fmt.Println(len(fileInfoList))
for i := range fileInfoList {
filePathList = append(filePathList, dirname+"/"+fileInfoList[i].Name())
}
logrus.Info(filePathList, "case1")
} else {
logrus.Info(" The file list name is not empty ")
content, err := ioutil.ReadFile(filepath)
if err != nil {
panic(err)
}
filePathList = strings.Split(strings.TrimSpace(string(content)), "\r\n")
logrus.Info(filePathList, "case2")
}
}
f := excelize.NewFile()
logrus.Info("this function is used to getData")
start := 0
for _, filePath := range filePathList {
// step1: get data
logrus.Info(filePath)
target := getData(filePath)
logrus.Info(target, len(target))
titleTmp := "A" + strconv.Itoa(start+1)
if err := f.SetCellDefault(sheetName, titleTmp, filePath); err != nil {
logrus.Println(err, "err")
return
}
// step2: Write cells
if res := writeData(f, sheetName, start+1, target); res != true {
logrus.Println(res, "err")
return
}
// step3: merge cell
firstString := "A" + strconv.Itoa(start+1)
start += len(target)
endString := "A" + strconv.Itoa(start)
logrus.Println(firstString, endString)
if err := f.MergeCell(sheetName, firstString, endString); err != nil {
logrus.Println(" Failed to merge cells ", err)
return
}
// step4: Add color
// Table fill color
style, err := f.NewStyle(&excelize.Style{
Alignment: &excelize.Alignment{
Horizontal: "center", Vertical: "center"},
Fill: excelize.Fill{
Type: "pattern", Color: []string{
"#FFFF00"}, Pattern: 1},
})
if err != nil {
logrus.Println(err)
return
}
err = f.SetCellStyle(sheetName, "A1", endString, style)
if err := f.SetColWidth(sheetName, "A", "A", 75); err != nil {
logrus.Println(err)
return
}
}
// Save the file according to the specified path
now := time.Now() // Get the current time
timeString := now.Format("2006_01_02_15_04")
if err := f.SaveAs("target1_" + timeString + ".xlsx"); err != nil {
logrus.Println(" preservation Book1.xlsx Failure ", err)
return
}
}
Reference resources :
https://xuri.me/excelize/zh-hans/sheet.html
边栏推荐
- (top) pretty girl binary color code portal
- Binary search (half search)
- Basic series of SHEL script (III) for while loop
- Unforgettable summary of 2021
- Install deeptools in CONDA mode
- Netease to B, soft outside, hard in
- Steps and FAQs of connecting windows Navicat to Alibaba cloud server MySQL
- Powermanagerservice (I) - initialization
- 并查集理论讲解和代码实现
- An article was opened to test the real situation of outsourcing companies
猜你喜欢

Unforgettable summary of 2021

Daily Practice:Codeforces Round #794 (Div. 2)(A~D)

Jenkins reported an error. Illegal character: '\ufeff'. Class, interface or enum are required

Shadowless cloud desktop - online computer
![[vscode] prohibit the pylance plug-in from automatically adding import](/img/a7/d96c0c4739ff68356c15bafbbb1328.jpg)
[vscode] prohibit the pylance plug-in from automatically adding import

Matrix and TMB package version issues in R

Light up the running light, rough notes for beginners (1)

Concurrent programming - deadlock troubleshooting and handling

Solve tensorfow GPU modulenotfounderror: no module named 'tensorflow_ core. estimator‘
![[software testing] 03 -- overview of software testing](/img/1e/0b6458160e34e43f021ea4797de70a.jpg)
[software testing] 03 -- overview of software testing
随机推荐
SD_ CMD_ RECEIVE_ SHIFT_ REGISTER
目标检测系列——Faster R-CNN原理详解
Jenkins reported an error. Illegal character: '\ufeff'. Class, interface or enum are required
Docker installs MySQL and uses Navicat to connect
Inftnews | drink tea and send virtual stocks? Analysis of Naixue's tea "coin issuance"
Course learning accumulation ppt
Do you choose pandas or SQL for the top 1 of data analysis in your mind?
Typescript get timestamp
docker安装mysql并使用navicat连接
Implementation of one-dimensional convolutional neural network CNN based on FPGA (VIII) implementation of activation layer
2022 PMP project management examination agile knowledge points (7)
玩转gRPC—深入概念与原理
[framework] multi learner
Powermanagerservice (I) - initialization
【idea】Could not autowire. No beans of xxx type found
I 用c l 栈与队列的相互实现
Explanation of parallel search set theory and code implementation
Machine learning Seaborn visualization
Pytorch has been installed in anaconda, and pycharm normally runs code, but vs code displays no module named 'torch‘
Rough notes of C language (1)