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