在日常工作中,經常會有導出 excel 表格的功能,下面我們就簡單的使用 Excelize 來導出 excel 文件。
Excelize 是 Go 語言編寫的用於操作 Office Excel 文檔基礎庫,基於 ECMA-376,ISO/IEC 29500 國際標准。可以使用它來讀取、寫入由 Microsoft Excel™ 2007 及以上版本創建的電子表格文檔。支持 XLSX / XLSM / XLTM / XLTX 等多種文檔格式,高度兼容帶有樣式、圖片(表)、透視表、切片器等復雜組件的文檔,並提供流式讀寫 API,用於處理包含大規模數據的工作簿。可應用於各類報表平台、雲計算、邊緣計算等系統。使用本類庫要求使用的 Go 語言為 1.15 或更高版本。
github: github.com/xuri/excelize
安裝
go get github.com/xuri/excelize // 如果使用 Go Modules 管理軟件包,可以用下面的命令來安裝最新版本 go get github.com/xuri/excelize/v2
創建 Excel 文檔
f := excelize.NewFile()// 設置單元格的值 // 這里設置表頭 f.SetCellValue("Sheet1", "A1", "序號") f.SetCellValue("Sheet1", "B1", "名稱") line := 1 fruits := getFruits() // 循環寫入數據 for _, v := range fruits { line++ f.SetCellValue("Sheet1", fmt.Sprintf("A%d", line), v.ID) f.SetCellValue("Sheet1", fmt.Sprintf("B%d", line), v.Name) } // 保存文件 if err := f.SaveAs("fruits.xlsx"); err != nil { fmt.Println(err) }
導出的文件內容是:
設置工作簿的列寬和行高
// 設置列寬 f.SetColWidth("Sheet1", "A", "C", 20) // 設置表頭行高 f.SetRowHeight("Sheet1", 1, 30)
這樣並不好看,接下來繼續設置單元格樣式
設置單元格樣式
1.設置表頭字體加粗、文字水平並且垂直居中、字體、顏色。
2.設置行的字體樣式默認是水平垂直居中,但是單價列的值必須靠左
下面是實現代碼
// 設置表頭樣式 headStyleID, _ := f.NewStyle(`{ "font":{ "color":"#333333", "bold":true, "size":16, "family":"arial" }, "alignment":{ "vertical":"center", "horizontal":"center" } }`) // 設置行樣式 rowStyleID, _ := f.NewStyle(`{ "font":{ "color":"#666666", "size":13, "family":"arial" }, "alignment":{ "vertical":"center", "horizontal":"center" } }`) f.SetCellStyle("Sheet1", "A1", "C1", headStyleID) textLeftStyleID, _ := f.NewStyle(`{ "alignment":{ "horizontal":"left" } }`) for _, v := range fruits { line++ f.SetCellValue("Sheet1", fmt.Sprintf("A%d", line), v.ID) f.SetCellValue("Sheet1", fmt.Sprintf("B%d", line), v.Name) f.SetCellValue("Sheet1", fmt.Sprintf("C%d", line), v.Price) // 設置行樣式 f.SetCellStyle("Sheet1", fmt.Sprintf("A%d", line), fmt.Sprintf("C%d", line), rowStyleID) f.SetCellStyle("Sheet1", fmt.Sprintf("C%d", line), fmt.Sprintf("C%d", line), textLeftStyleID) }
結果:
表格數據源
type fruit struct { ID uint Name string Price float64 } func getFruits() []*fruit { return []*fruit{ &fruit{ ID: 1, Name: "蘋果", Price: 8, }, &fruit{ ID: 2, Name: "雪梨", Price: 5, }, &fruit{ ID: 3, Name: "香蕉", Price: 3, }, } }
簡單粗暴的貼代碼。。。希望有點幫助