当前位置:网站首页>使用go语言读取txt文件写入excel中
使用go语言读取txt文件写入excel中
2022-07-05 07:25:00 【幽默的荆轲君】
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("写入行单元格失败", err)
return false
}
}
return true
}
func getFilePath() (dirname, filepath string) {
/* 定义变量接收控制台参数 */
文件夹名
//var dirname string
//
文件名
//var path string
flag.StringVar(&dirname, "d", "", "存放文件的文件夹名 默认为空")
flag.StringVar(&filepath, "f", "", "按特定顺序写的文件列表名,默认为空")
flag.Parse()
return dirname, filepath
}
func main() {
var filePathList []string
sheetName := "Sheet1"
if dirname, filepath := getFilePath(); dirname == "" && filepath == "" {
logrus.Info("执行./main -h 查看用法")
os.Exit(-1)
} else {
if dirname != "" {
logrus.Info("dirname不为空")
//获取文件或目录相关信息
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("文件列表名不为空")
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: 写入单元格
if res := writeData(f, sheetName, start+1, target); res != true {
logrus.Println(res, "err")
return
}
// step3: 合并单元格
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("合并单元格失败", err)
return
}
// step4: 加颜色
// 表格填充颜色
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
}
}
// 根据指定路径保存文件
now := time.Now() //获取当前时间
timeString := now.Format("2006_01_02_15_04")
if err := f.SaveAs("target1_" + timeString + ".xlsx"); err != nil {
logrus.Println("保存Book1.xlsx失败", err)
return
}
}
参考:
https://xuri.me/excelize/zh-hans/sheet.html
边栏推荐
- Unconventional ending disconnected from the target VM, address: '127.0.0.1:62635', transport: 'socket‘
- Anaconda navigator click open no response, can not start error prompt attributeerror: 'STR' object has no attribute 'get‘
- UNIX commands often used in work
- 1290_ Implementation analysis of prvtaskistasksuspended() interface in FreeRTOS
- 剑指 Offer 56 数组中数字出现的次数(异或)
- Basic series of SHEL script (I) variables
- Powermanagerservice (I) - initialization
- CADD课程学习(6)-- 获得已有的虚拟化合物库(Drugbank、ZINC)
- Eclipse project recompile, clear cache
- Ugnx12.0 initialization crash, initialization error (-15)
猜你喜欢
611. 有效三角形的个数
Steps and FAQs of connecting windows Navicat to Alibaba cloud server MySQL
How to deal with excessive memory occupation of idea and Google browser
M2dgr slam data set of multi-source and multi scene ground robot
Intelligent target detection 59 -- detailed explanation of pytoch focal loss and its implementation in yolov4
HDU1231 最大连续子序列(分治or动规or双指针)
行测--资料分析--fb--高照老师
Hdu1231 maximum continuous subsequence (divide and conquer or dynamic gauge or double pointer)
SD_ CMD_ RECEIVE_ SHIFT_ REGISTER
Shadowless cloud desktop - online computer
随机推荐
iNFTnews | 喝茶送虚拟股票?浅析奈雪的茶“发币”
Netease to B, soft outside, hard in
Database SQL practice 4. Find the last of employees in all assigned departments_ Name and first_ name
HDU1232 畅通工程(并查集)
玩转gRPC—深入概念与原理
SD_ CMD_ SEND_ SHIFT_ REGISTER
目标检测系列——Faster R-CNN原理详解
Jenkins reported an error. Illegal character: '\ufeff'. Class, interface or enum are required
Basic series of SHEL script (II) syntax + operation + judgment
Selenium element positioning
Simple operation of running water lamp (keil5)
arcpy. SpatialJoin_ Analysis spatial connection analysis
Docker installs MySQL and uses Navicat to connect
Inftnews | drink tea and send virtual stocks? Analysis of Naixue's tea "coin issuance"
Qu'est - ce que l'hydroxyde de sodium?
Idea push project to code cloud
[vscode] prohibit the pylance plug-in from automatically adding import
Chapter 2: try to implement a simple bean container
[untitled]
(tool use) how to make the system automatically match and associate to database fields by importing MySQL from idea and writing SQL statements