package main
import (
"fmt"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/xuri/excelize/v2"
)
var wg sync.WaitGroup
func main() {
wg.Add(2)
go writeToCsv()
go writeToExcelDirectly()
wg.Wait()
}
func writeToCsv() {
//数据写入到csv文件
t1 := time.Now().UnixNano()
//首行
var titles string
titles = "姓名,年龄,爱好\n"
var stringBuilder strings.Builder
stringBuilder.WriteString(titles)
var i int
for i = 0; i < 1000000; i++ {
dataString := fmt.Sprintf("张三%d,%d,蹦极%d\n", i+1, i+1, i+1)
stringBuilder.WriteString(dataString)
}
filename := "./test.csv"
file, _ := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, os.ModeAppend|os.ModePerm)
dataString := stringBuilder.String()
file.WriteString(dataString)
file.Close()
t2 := time.Now().UnixNano()
t := t2 - t1
fmt.Printf("writeToCsv总共%d条数据,总耗时%d毫秒\n", i, t/1000000)
wg.Done()
}
func writeToExcelDirectly() {
//数据写入到excel文件
t1 := time.Now().UnixNano()
f := excelize.NewFile()
defer f.Close()
// 创建一个工作表
index := f.NewSheet("Sheet1")
// 设置单元格的值
f.SetCellValue("Sheet1", "A1", "姓名")
f.SetCellValue("Sheet1", "B1", "年龄")
f.SetCellValue("Sheet1", "C1", "爱好")
var indexA, indexB, indexC string
var i int
for i = 0; i < 10000; i++ {
indexA = fmt.Sprintf("A%v", i+2)
indexB = fmt.Sprintf("B%v", i+2)
indexC = fmt.Sprintf("C%v", i+2)
f.SetCellValue("Sheet1", indexA, "张三"+strconv.Itoa(i))
f.SetCellValue("Sheet1", indexB, i)
f.SetCellValue("Sheet1", indexC, "游泳"+strconv.Itoa(i))
}
// 设置工作簿的默认工作表
f.SetActiveSheet(index)
// 根据指定路径保存文件
name := "test.xlsx"
if err := f.SaveAs(name); err != nil {
panic(err)
}
t2 := time.Now().UnixNano()
t := t2 - t1
fmt.Printf("writeToExcelDirectly总共%d条数据,总耗时%d毫秒\n", i, t/1000000)
wg.Done()
}