二维簇状柱形图

例如,创建如下效果的二维簇状柱形图:

使用 Go 语言在 Excel 文档中创建二维簇状柱形图

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/360EntSecGroup-Skylar/excelize"
  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": "col",
  20. "series": [
  21. {
  22. "name": "Sheet1!$A$2",
  23. "categories": "",
  24. "values": "Sheet1!$B$2:$D$2"
  25. },
  26. {
  27. "name": "Sheet1!$A$3",
  28. "categories": "Sheet1!$B$1:$D$1",
  29. "values": "Sheet1!$B$3:$D$3"
  30. },
  31. {
  32. "name": "Sheet1!$A$4",
  33. "categories": "Sheet1!$B$1:$D$1",
  34. "values": "Sheet1!$B$4:$D$4"
  35. }],
  36. "format":
  37. {
  38. "x_scale": 1.0,
  39. "y_scale": 1.0,
  40. "x_offset": 15,
  41. "y_offset": 10,
  42. "print_obj": true,
  43. "lock_aspect_ratio": false,
  44. "locked": false
  45. },
  46. "legend":
  47. {
  48. "position": "left",
  49. "show_legend_key": false
  50. },
  51. "title":
  52. {
  53. "name": "Fruit 2D Column Chart"
  54. },
  55. "plotarea":
  56. {
  57. "show_bubble_size": true,
  58. "show_cat_name": false,
  59. "show_leader_lines": false,
  60. "show_percent": true,
  61. "show_series_name": true,
  62. "show_val": true
  63. },
  64. "show_blanks_as": "zero"
  65. }`); err != nil {
  66. fmt.Println(err)
  67. }
  68. // 保存工作簿
  69. if err := f.SaveAs("Book1.xlsx"); err != nil {
  70. fmt.Println(err)
  71. }
  72. }