【Golang】使用gin框架导出excel和csv文件
目录
- 1、背景
- 2、go库
- 【1】excel库下载
- 【2】csv标准库
- 3、代码示例
- 4、使用方法
1、背景
项目中可能会遇到导入导出一批数据的功能,对于批量大数据可能用表格的方式直观性更好,所以本篇文件来讲一下go中导出excel和csv文件的方式。
2、go库
【1】excel库下载
go get -u github.com/xuri/excelize/v2
【2】csv标准库
encoding/csv
3、代码示例
func main() {r := gin.Default()r.GET("/download", func(c *gin.Context) {fileType := c.Query("type") // 获取请求参数csv或excelswitch strings.ToLower(fileType) {case "csv":downloadCSV(c)case "excel":downloadExcel(c)default:c.JSON(http.StatusBadRequest, gin.H{"error": "invalid type parameter, use 'csv' or 'excel'"})}})r.Run(":8080")
}func downloadCSV(c *gin.Context) {// 设置响应头 - 解决乱码和中文文件名问题filename := url.QueryEscape("测试.csv")c.Header("Content-Disposition", "attachment; filename*=UTF-8''"+filename)c.Header("Content-Type", "text/csv; charset=utf-8")// 写入UTF-8 BOM头,防止中文乱码(可选,某些旧版Excel需要)_, _ = c.Writer.Write([]byte{0xEF, 0xBB, 0xBF})// 创建CSV写入器writer := csv.NewWriter(c.Writer)defer writer.Flush()// 写入表头_ = writer.Write([]string{"姓名", "年龄"})// 写入数据行data := [][]string{{"xxx", "18"},{"yyy", "19"},{"zzz", "20"},}for _, row := range data {_ = writer.Write(row)}
}func downloadExcel(c *gin.Context) {// 创建Excel文件f := excelize.NewFile()defer f.Close()// 创建工作表index, _ := f.NewSheet("Sheet1")// 设置表头_ = f.SetCellValue("Sheet1", "A1", "姓名")_ = f.SetCellValue("Sheet1", "B1", "年龄")// 设置数据data := [][]interface{}{{"xxx", "18"},{"yyy", "19"},{"zzz", "20"},}for i, row := range data {_ = f.SetCellValue("Sheet1", "A"+strconv.Itoa(i+2), row[0])_ = f.SetCellValue("Sheet1", "B"+strconv.Itoa(i+2), row[1])}// 设置活动工作表f.SetActiveSheet(index)// 设置响应头 - 解决中文文件名问题filename := url.QueryEscape("测试.xlsx")c.Header("Content-Type", "application/octet-stream")c.Header("Content-Disposition", "attachment; filename*=UTF-8''"+filename)// 写入响应_ = f.Write(c.Writer)
}
4、使用方法
浏览器上输入http://127.0.0.1:8080/download?type=excel下载excel文件,浏览器上输入http://127.0.0.1:8080/download?type=csv下载csv文件,下载完之后可以在下载目录看到如下文件:
xxx@A030414-NC MINGW64 /d/谷歌浏览器下载文件
$ ls 测试.*
测试.csv 测试.xlsx