散点图

例如,创建如下效果的散点图:

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

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/xuri/excelize/v2"
  5. )
  6. func main() {
  7. f := excelize.NewFile()
  8. defer func() {
  9. if err := f.Close(); err != nil {
  10. fmt.Println(err)
  11. }
  12. }()
  13. for idx, row := range [][]interface{}{
  14. {nil, "Apple", "Orange", "Pear"},
  15. {"Small", 2, 3, 3},
  16. {"Normal", 5, 2, 4},
  17. {"Large", 6, 7, 8},
  18. } {
  19. cell, err := excelize.CoordinatesToCellName(1, idx+1)
  20. if err != nil {
  21. fmt.Println(err)
  22. return
  23. }
  24. if err := f.SetSheetRow("Sheet1", cell, &row); err != nil {
  25. fmt.Println(err)
  26. return
  27. }
  28. }
  29. if err := f.AddChart("Sheet1", "E1", &excelize.Chart{
  30. Type: excelize.Scatter,
  31. Series: []excelize.ChartSeries{
  32. {
  33. Name: "Sheet1!$A$2",
  34. Categories: "Sheet1!$B$1:$D$1",
  35. Values: "Sheet1!$B$2:$D$2",
  36. },
  37. {
  38. Name: "Sheet1!$A$3",
  39. Categories: "Sheet1!$B$1:$D$1",
  40. Values: "Sheet1!$B$3:$D$3",
  41. },
  42. {
  43. Name: "Sheet1!$A$4",
  44. Categories: "Sheet1!$B$1:$D$1",
  45. Values: "Sheet1!$B$4:$D$4",
  46. },
  47. },
  48. Format: excelize.GraphicOptions{
  49. OffsetX: 15,
  50. OffsetY: 10,
  51. },
  52. Legend: excelize.ChartLegend{
  53. Position: "left",
  54. },
  55. Title: []excelize.RichTextRun{
  56. {
  57. Text: "Fruit Scatter Chart",
  58. },
  59. },
  60. PlotArea: excelize.ChartPlotArea{
  61. ShowCatName: false,
  62. ShowLeaderLines: false,
  63. ShowPercent: true,
  64. ShowSerName: true,
  65. ShowVal: true,
  66. },
  67. ShowBlanksAs: "zero",
  68. }); err != nil {
  69. fmt.Println(err)
  70. return
  71. }
  72. // 保存工作簿
  73. if err := f.SaveAs("Book1.xlsx"); err != nil {
  74. fmt.Println(err)
  75. }
  76. }