在 Excel 文档中创建图表

使用 Excelize 生成图表十分简单,仅需几行代码。您可以根据工作表中的已有数据构建图表,或向工作表中添加数据并创建图表。

在 Excel 文档中创建图表

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/360EntSecGroup-Skylar/excelize"
  5. )
  6. func main() {
  7. categories := map[string]string{"A2": "Small", "A3": "Normal", "A4": "Large", "B1": "Apple", "C1": "Orange", "D1": "Pear"}
  8. values := map[string]int{"B2": 2, "C2": 3, "D2": 3, "B3": 5, "C3": 2, "D3": 4, "B4": 6, "C4": 7, "D4": 8}
  9. f := excelize.NewFile()
  10. for k, v := range categories {
  11. f.SetCellValue("Sheet1", k, v)
  12. }
  13. for k, v := range values {
  14. f.SetCellValue("Sheet1", k, v)
  15. }
  16. err := f.AddChart("Sheet1", "E1", `{"type":"col3DClustered","series":[{"name":"Sheet1!$A$2","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$2:$D$2"},{"name":"Sheet1!$A$3","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$3:$D$3"},{"name":"Sheet1!$A$4","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$4:$D$4"}],"title":{"name":"Fruit 3D Clustered Column Chart"}}`)
  17. if err != nil {
  18. fmt.Println(err)
  19. }
  20. // 根据指定路径保存文件
  21. err = f.SaveAs("./Book1.xlsx")
  22. if err != nil {
  23. fmt.Println(err)
  24. }
  25. }