💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
import "encoding/csv" csv读写逗号分隔值(csv)的文件。 一个csv分拣包含零到多条记录,每条记录一到多个字段。每个记录用换行符分隔。最后一条记录后面可以有换行符,也可以没有。 ~~~ func NewWriter(w io.Writer) *Writer // NewWriter返回一个写入w的*Writer。 func (w *Writer) Write(record []string) (err error) // 向w中写入一条记录,会自行添加必需的引号。记录是字符串切片,每个字符串代表一个字段。 func (w *Writer) Flush() // 将缓存中的数据写入底层的io.Writer。要检查Flush时是否发生错误的话,应调用Error方法。 func (w *Writer) WriteAll(records [][]string) (err error) // WriteAll方法使用Write方法向w写入多条记录,并在最后调用Flush方法清空缓存。 ~~~ 代码实现: ~~~ package main import ( "encoding/csv" "math/rand" "os" "strconv" ) func main() { file, err := os.Create("./test.xls") if err != nil { panic(err) } defer func(file *os.File) { file.Close() }(file) file.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM w := csv.NewWriter(file) w.Write([]string{"编号", "姓名", "年龄"}) for i := 1; i < 11; i++ { num := strconv.FormatInt(int64(i), 10) age := strconv.FormatInt(int64(rand.Intn(100)), 10) w.Write([]string{num, "name" + num, age}) } w.Flush() records := [][]string{} for i := 11; i < 21; i++ { num := strconv.FormatInt(int64(i), 10) age := strconv.FormatInt(int64(rand.Intn(100)), 10) str := []string{num, "name" + num, age} records = append(records, str) } w.WriteAll(records) } ~~~