Files
be.ems/lib/core/file/csv.go
2023-09-08 21:54:47 +08:00

44 lines
878 B
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package file
import (
"encoding/csv"
"os"
"path/filepath"
"ems.agt/lib/log"
)
// 写入CSV文件需要转换数据
// 例如:
// data := [][]string{}
// data = append(data, []string{"姓名", "年龄", "城市"})
// data = append(data, []string{"1", "2", "3"})
// err := file.WriterCSVFile(data, filePath)
func WriterCSVFile(data [][]string, filePath string) error {
// 获取文件所在的目录路径
dirPath := filepath.Dir(filePath)
// 确保文件夹路径存在
err := os.MkdirAll(dirPath, os.ModePerm)
if err != nil {
log.Errorf("创建文件夹失败 CreateFile %v", err)
}
// 创建或打开文件
file, err := os.Create(filePath)
if err != nil {
return err
}
defer file.Close()
// 创建CSV编写器
writer := csv.NewWriter(file)
defer writer.Flush()
// 写入数据
for _, row := range data {
writer.Write(row)
}
return nil
}