饼图

例如,创建如下效果的饼图:

使用 Go 语言在 Excel 文档中创建饼图

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/xuri/excelize/v2"
  5. )
  6. func main() {
  7. categories := map[string]string{
  8. "A2": "Small", "A3": "Normal", "A4": "Large", "B1": "Apple", "C1": "Orange", "D1": "Pear"}
  9. values := map[string]int{
  10. "B2": 2, "C2": 3, "D2": 3, "B3": 5, "C3": 2, "D3": 4, "B4": 6, "C4": 7, "D4": 8}
  11. f := excelize.NewFile()
  12. for k, v := range categories {
  13. f.SetCellValue("Sheet1", k, v)
  14. }
  15. for k, v := range values {
  16. f.SetCellValue("Sheet1", k, v)
  17. }
  18. if err := f.AddChart("Sheet1", "E1", `{
  19. "type": "pie",
  20. "series": [
  21. {
  22. "name": "Sheet1!$A$2",
  23. "categories": "Sheet1!$B$1:$D$1",
  24. "values": "Sheet1!$B$2:$D$2"
  25. }],
  26. "format":
  27. {
  28. "x_scale": 1.0,
  29. "y_scale": 1.0,
  30. "x_offset": 15,
  31. "y_offset": 10,
  32. "print_obj": true,
  33. "lock_aspect_ratio": false,
  34. "locked": false
  35. },
  36. "legend":
  37. {
  38. "position": "bottom",
  39. "show_legend_key": false
  40. },
  41. "title":
  42. {
  43. "name": "Fruit Pie Chart"
  44. },
  45. "plotarea":
  46. {
  47. "show_bubble_size": true,
  48. "show_cat_name": false,
  49. "show_leader_lines": false,
  50. "show_percent": true,
  51. "show_series_name": false,
  52. "show_val": false
  53. },
  54. "show_blanks_as": "gap"
  55. }`); err != nil {
  56. fmt.Println(err)
  57. }
  58. // 保存工作簿
  59. if err := f.SaveAs("Book1.xlsx"); err != nil {
  60. fmt.Println(err)
  61. }
  62. }