在 Excel 文档中创建图表

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

在 Excel 文档中创建图表

  1. package main
  2. import "github.com/360EntSecGroup-Skylar/excelize"
  3. func main() {
  4. categories := map[string]string{"A2": "Small", "A3": "Normal", "A4": "Large", "B1": "Apple", "C1": "Orange", "D1": "Pear"}
  5. values := map[string]int{"B2": 2, "C2": 3, "D2": 3, "B3": 5, "C3": 2, "D3": 4, "B4": 6, "C4": 7, "D4": 8}
  6. f := excelize.NewFile()
  7. for k, v := range categories {
  8. f.SetCellValue("Sheet1", k, v)
  9. }
  10. for k, v := range values {
  11. f.SetCellValue("Sheet1", k, v)
  12. }
  13. if 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"}}`); err != nil {
  14. println(err.Error())
  15. return
  16. }
  17. // 根据指定路径保存文件
  18. if err := f.SaveAs("Book1.xlsx"); err != nil {
  19. println(err.Error())
  20. }
  21. }