折线图

例如,创建如下效果的折线图:

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