饼图

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

使用 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. {"Apple", "Orange", "Pear"},
  15. {2, 3, 3},
  16. } {
  17. cell, err := excelize.CoordinatesToCellName(1, idx+1)
  18. if err != nil {
  19. fmt.Println(err)
  20. return
  21. }
  22. if err := f.SetSheetRow("Sheet1", cell, &row); err != nil {
  23. fmt.Println(err)
  24. return
  25. }
  26. }
  27. if err := f.AddChart("Sheet1", "E1", &excelize.Chart{
  28. Type: excelize.Pie,
  29. Series: []excelize.ChartSeries{
  30. {
  31. Name: "数量",
  32. Categories: "Sheet1!$A$1:$C$1",
  33. Values: "Sheet1!$A$2:$C$2",
  34. },
  35. },
  36. Format: excelize.GraphicOptions{
  37. OffsetX: 15,
  38. OffsetY: 10,
  39. },
  40. Title: []excelize.RichTextRun{
  41. {
  42. Text: "三维饼图",
  43. },
  44. },
  45. PlotArea: excelize.ChartPlotArea{
  46. ShowPercent: true,
  47. },
  48. }); err != nil {
  49. fmt.Println(err)
  50. return
  51. }
  52. // 保存工作簿
  53. if err := f.SaveAs("Book1.xlsx"); err != nil {
  54. fmt.Println(err)
  55. }
  56. }