最近有个需求是把看广告的日志转成excel
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"github.com/xuri/excelize/v2"
"os"
"time"
)
// Ad 广告
type Ad struct {
OpenId string `json:"OpenId"`
Uid int64 `json:"id"`
Time string `json:"time"`
}
func textToExcel2(textFile, excelFile, fileName string) error {
// 打开文本文件
file, err := os.Open(textFile)
if err != nil {
return err
}
defer file.Close()
// 创建新的Excel文件
f := excelize.NewFile()
sheetName := "Sheet1"
// 写入表头内容
_ = f.SetCellValue(sheetName, "A1", "openId")
_ = f.SetCellValue(sheetName, "B1", "用户id")
_ = f.SetCellValue(sheetName, "C1", "看广告时间")
// 逐行读取文本文件并将内容写入Excel文件
scanner := bufio.NewScanner(file)
rowIndex := 2
for scanner.Scan() {
line := scanner.Text()
var ad Ad
if err := json.Unmarshal([]byte(line), &ad); err != nil {
fmt.Println("Error decoding JSON:", err)
continue
}
_ = f.SetCellValue(sheetName, fmt.Sprintf("A%d", rowIndex), ad.OpenId)
_ = f.SetCellValue(sheetName, fmt.Sprintf("B%d", rowIndex), ad.Uid)
_ = f.SetCellValue(sheetName, fmt.Sprintf("C%d", rowIndex), ad.Time)
rowIndex++
}
// 检查是否有读取文本文件时的错误
if err := scanner.Err(); err != nil {
return err
}
excelFileEnd := excelFile + getPreDay() + "-" + fileName + ".xlsx"
// 保存Excel文件
if err := f.SaveAs(excelFileEnd); err != nil {
return err
}
return nil
}
func main() {
// 替换以下文件路径为实际的文本文件路径和输出Excel文件路径
path := flag.String("path", "/usr/share/nginx/html/server-api/runtime/logs/", "请输入日志的绝对路径")
outPath := flag.String("outPath", "/usr/share/nginx/html/server-api/runtime/logs/", "请输入生成excel的绝对路径")
fileName := flag.String("fileName", "emp", "请输入生成文件的名字")
name := flag.String("name", "ad", "请输入日志的前缀")
flag.Parse()
//日志的绝对路径
textFilePath := *path + *name + "-" + getPreDay() + ".log"
//生成的excel的路径
if _, err := os.Stat(*outPath); os.IsNotExist(err) {
// 文件夹不存在,创建文件夹
err := os.MkdirAll(*outPath, 0755)
if err != nil {
fmt.Println("创建文件夹失败:", err)
} else {
fmt.Println("文件夹创建成功!")
}
}
err := textToExcel2(textFilePath, *outPath, *fileName)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("数据写入到Excel成功")
}
// 获取前一天日期
func getPreDay() string {
timeNow := time.Now().Add(-24 * time.Hour)
return timeNow.Format("2006-01-02")
}
go run main.go -fileName="游戏名字" -path=/usr/share/nginx/html/xxx/runtime/logs/ -outPath=/usr/share/nginx/html/excel/游戏名字/
标签:return,nil,err,fmt,excel,fileName,Golang,sheetName,写到
From: https://www.cnblogs.com/qcy-blog/p/17835923.html