You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.1 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package example
  2. import (
  3. "errors"
  4. "fmt"
  5. "strconv"
  6. "github.com/flipped-aurora/gin-vue-admin/server/global"
  7. "github.com/flipped-aurora/gin-vue-admin/server/model/system"
  8. "github.com/xuri/excelize/v2"
  9. )
  10. type ExcelService struct{}
  11. func (exa *ExcelService) ParseInfoList2Excel(infoList []system.SysBaseMenu, filePath string) error {
  12. excel := excelize.NewFile()
  13. excel.SetSheetRow("Sheet1", "A1", &[]string{"ID", "路由Name", "路由Path", "是否隐藏", "父节点", "排序", "文件名称"})
  14. for i, menu := range infoList {
  15. axis := fmt.Sprintf("A%d", i+2)
  16. excel.SetSheetRow("Sheet1", axis, &[]interface{}{
  17. menu.ID,
  18. menu.Name,
  19. menu.Path,
  20. menu.Hidden,
  21. menu.ParentId,
  22. menu.Sort,
  23. menu.Component,
  24. })
  25. }
  26. err := excel.SaveAs(filePath)
  27. return err
  28. }
  29. func (exa *ExcelService) ParseExcel2InfoList() ([]system.SysBaseMenu, error) {
  30. skipHeader := true
  31. fixedHeader := []string{"ID", "路由Name", "路由Path", "是否隐藏", "父节点", "排序", "文件名称"}
  32. file, err := excelize.OpenFile(global.GVA_CONFIG.Excel.Dir + "ExcelImport.xlsx")
  33. if err != nil {
  34. return nil, err
  35. }
  36. menus := make([]system.SysBaseMenu, 0)
  37. rows, err := file.Rows("Sheet1")
  38. if err != nil {
  39. return nil, err
  40. }
  41. for rows.Next() {
  42. row, err := rows.Columns()
  43. if err != nil {
  44. return nil, err
  45. }
  46. if skipHeader {
  47. if exa.compareStrSlice(row, fixedHeader) {
  48. skipHeader = false
  49. continue
  50. } else {
  51. return nil, errors.New("Excel格式错误")
  52. }
  53. }
  54. if len(row) != len(fixedHeader) {
  55. continue
  56. }
  57. id, _ := strconv.Atoi(row[0])
  58. hidden, _ := strconv.ParseBool(row[3])
  59. sort, _ := strconv.Atoi(row[5])
  60. menu := system.SysBaseMenu{
  61. GVA_MODEL: global.GVA_MODEL{
  62. ID: uint(id),
  63. },
  64. Name: row[1],
  65. Path: row[2],
  66. Hidden: hidden,
  67. ParentId: row[4],
  68. Sort: sort,
  69. Component: row[6],
  70. }
  71. menus = append(menus, menu)
  72. }
  73. return menus, nil
  74. }
  75. func (exa *ExcelService) compareStrSlice(a, b []string) bool {
  76. if len(a) != len(b) {
  77. return false
  78. }
  79. if (b == nil) != (a == nil) {
  80. return false
  81. }
  82. for key, value := range a {
  83. if value != b[key] {
  84. return false
  85. }
  86. }
  87. return true
  88. }