Go API中如何将结构体数组转为PDF与Excel文件?
Go实现结构体数组转Excel/PDF及对应库推荐
在Go生态里,确实有能实现类似Python pandas中dataframe.to_excel/dataframe.to_csv功能的库,针对Excel和PDF导出需求,以下是实用的库推荐及适配你现有代码的示例:
Excel导出:excelize
excelize是Go生态中最流行的Excel文件处理库,支持读写.xlsx格式文件,能快速将结构体数组转换为标准Excel表格。
示例代码(适配你的HTTP接口场景)
package main import ( "github.com/gorilla/mux" "github.com/xuri/excelize/v2" "log" "net/http" ) type Test struct { ID int `json:"ID"` Name string `json:"Name"` Delete string `json:"Delete"` } func main() { r := mux.NewRouter().StrictSlash(true) r.HandleFunc("/export-excel", func(rw http.ResponseWriter, req *http.Request) { tests := []Test{ {ID: 1, Name: "a", Delete: "delete"}, {ID: 2, Name: "b", Delete: "delete"}, } // 初始化Excel文件 f := excelize.NewFile() defer func() { if err := f.Close(); err != nil { log.Println(err) } }() // 写入表头 headers := []string{"ID", "Name", "Delete"} for colIdx, header := range headers { cell, _ := excelize.CoordinatesToCellName(colIdx+1, 1) f.SetCellValue("Sheet1", cell, header) } // 填充结构体数据到表格 for rowIdx, test := range tests { rowNum := rowIdx + 2 // 从第二行开始写入数据 f.SetCellValue("Sheet1", "A"+string(rune(rowNum+'0')), test.ID) f.SetCellValue("Sheet1", "B"+string(rune(rowNum+'0')), test.Name) f.SetCellValue("Sheet1", "C"+string(rune(rowNum+'0')), test.Delete) } // 设置响应头,触发浏览器下载 rw.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") rw.Header().Set("Content-Disposition", "attachment; filename=test_data.xlsx") // 将Excel内容写入HTTP响应 if err := f.Write(rw); err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } }).Methods(http.MethodGet) log.Fatal(http.ListenAndServe(":8000", r)) }
PDF导出:gofpdf
gofpdf是一个轻量且易用的PDF生成库,支持创建表格、文本、图片等元素,适合将结构化数据转换为PDF格式的表格文档。
示例代码(适配你的HTTP接口场景)
package main import ( "github.com/gorilla/mux" "github.com/jung-kurt/gofpdf" "log" "net/http" "strconv" ) type Test struct { ID int `json:"ID"` Name string `json:"Name"` Delete string `json:"Delete"` } func main() { r := mux.NewRouter().StrictSlash(true) r.HandleFunc("/export-pdf", func(rw http.ResponseWriter, req *http.Request) { tests := []Test{ {ID: 1, Name: "a", Delete: "delete"}, {ID: 2, Name: "b", Delete: "delete"}, } // 初始化PDF实例 pdf := gofpdf.New("P", "mm", "A4", "") pdf.AddPage() pdf.SetFont("Arial", "B", 12) // 定义表格列宽与表头 colWidths := []float64{20, 30, 40} headers := []string{"ID", "Name", "Delete"} // 绘制表头(带灰色背景) pdf.SetFillColor(200, 200, 200) for i, header := range headers { pdf.CellFormat(colWidths[i], 7, header, "1", 0, "CM", true, 0, "") } pdf.Ln(-1) // 填充表格数据(交替行背景色) pdf.SetFont("Arial", "", 12) pdf.SetFillColor(240, 240, 240) alternateFill := false for _, test := range tests { pdf.CellFormat(colWidths[0], 6, strconv.Itoa(test.ID), "1", 0, "CM", alternateFill, 0, "") pdf.CellFormat(colWidths[1], 6, test.Name, "1", 0, "CM", alternateFill, 0, "") pdf.CellFormat(colWidths[2], 6, test.Delete, "1", 0, "CM", alternateFill, 0, "") pdf.Ln(-1) alternateFill = !alternateFill } // 设置响应头,触发浏览器下载 rw.Header().Set("Content-Type", "application/pdf") rw.Header().Set("Content-Disposition", "attachment; filename=test_data.pdf") // 将PDF内容写入HTTP响应 if err := pdf.Output(rw); err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } }).Methods(http.MethodGet) log.Fatal(http.ListenAndServe(":8000", r)) }
补充说明
你当前使用的gocsv就是Go生态中对应dataframe.to_csv的工具库,配合上述excelize和gofpdf,可以完整实现CSV、Excel、PDF三种格式的表格导出需求。
内容的提问来源于stack exchange,提问作者Barış Kılıç
相关产品推荐
相关产品推荐

