channel_export.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package controller
  2. import (
  3. "bytes"
  4. "net/http"
  5. "one-api/common"
  6. "one-api/model"
  7. "github.com/gin-gonic/gin"
  8. "github.com/xuri/excelize/v2"
  9. )
  10. func ExportChannels(c *gin.Context) {
  11. // 获取所有渠道数据
  12. channels, err := model.GetAllChannels(0, 0, true, false)
  13. if err != nil {
  14. common.ApiError(c, err)
  15. return
  16. }
  17. // 创建Excel文件
  18. f := excelize.NewFile()
  19. defer func() {
  20. if err := f.Close(); err != nil {
  21. common.SysError("Error closing Excel file: " + err.Error())
  22. }
  23. }()
  24. // 创建工作表
  25. sheetName := "Channels"
  26. f.SetSheetName("Sheet1", sheetName)
  27. // 设置表头
  28. headers := []string{
  29. "ID", "名称", "类型", "状态", "密钥", "组织", "测试模型",
  30. "权重", "创建时间", "测试时间", "响应时间", "基础URL", "其他",
  31. "余额", "余额更新时间", "模型", "分组", "已用配额",
  32. "模型映射", "状态码映射", "优先级", "自动禁用", "标签", "额外设置", "参数覆盖",
  33. }
  34. for i, header := range headers {
  35. cell, _ := excelize.CoordinatesToCellName(i+1, 1)
  36. f.SetCellValue(sheetName, cell, header)
  37. }
  38. // 填充数据
  39. for i, channel := range channels {
  40. row := i + 2 // 从第二行开始填充数据
  41. data := []interface{}{
  42. channel.Id,
  43. channel.Name,
  44. channel.Type,
  45. channel.Status,
  46. channel.Key,
  47. channel.OpenAIOrganization,
  48. channel.TestModel,
  49. channel.Weight,
  50. channel.CreatedTime,
  51. channel.TestTime,
  52. channel.ResponseTime,
  53. channel.BaseURL,
  54. channel.Other,
  55. channel.Balance,
  56. channel.BalanceUpdatedTime,
  57. channel.Models,
  58. channel.Group,
  59. channel.UsedQuota,
  60. channel.ModelMapping,
  61. channel.StatusCodeMapping,
  62. channel.Priority,
  63. channel.AutoBan,
  64. channel.Tag,
  65. channel.Setting,
  66. channel.ParamOverride,
  67. }
  68. for j, value := range data {
  69. cell, _ := excelize.CoordinatesToCellName(j+1, row)
  70. f.SetCellValue(sheetName, cell, value)
  71. }
  72. }
  73. // 设置响应头
  74. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  75. c.Header("Content-Disposition", "attachment; filename=channels.xlsx")
  76. c.Header("Cache-Control", "no-cache")
  77. // 将Excel文件写入缓冲区
  78. var buf bytes.Buffer
  79. if err := f.Write(&buf); err != nil {
  80. common.ApiError(c, err)
  81. return
  82. }
  83. // 返回Excel文件
  84. c.Data(http.StatusOK, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", buf.Bytes())
  85. }