二维堆积面积图

例如,创建如下效果的二维堆积面积图:

使用 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.AreaStacked,
  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. Title: []excelize.RichTextRun{
  53. {
  54. Text: "Fruit 2D Stacked Area Chart",
  55. },
  56. },
  57. PlotArea: excelize.ChartPlotArea{
  58. ShowCatName: false,
  59. ShowLeaderLines: false,
  60. ShowPercent: true,
  61. ShowSerName: true,
  62. ShowVal: true,
  63. },
  64. ShowBlanksAs: "zero",
  65. }); err != nil {
  66. fmt.Println(err)
  67. return
  68. }
  69. // 保存工作簿
  70. if err := f.SaveAs("Book1.xlsx"); err != nil {
  71. fmt.Println(err)
  72. }
  73. }