xlsx.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package sxlsx
  2. import (
  3. . "createindex/base"
  4. "log"
  5. "github.com/xuri/excelize/v2"
  6. )
  7. //源端读取对象,excel
  8. type (
  9. SXlsx struct {
  10. File string
  11. Sheet string
  12. //Fields []string //同步字段,这空默认全部
  13. Mfields map[string]string //字段映射
  14. Min int //最小行
  15. Max int //最大行
  16. }
  17. )
  18. func GetXlsx(file, sheet string, mfields map[string]string, min, max int) *SXlsx {
  19. return &SXlsx{
  20. File: file,
  21. Sheet: sheet,
  22. //Fields: fields,
  23. Mfields: mfields,
  24. Min: min,
  25. Max: max,
  26. }
  27. }
  28. func (m *SXlsx) Find(d Direct) {
  29. f, err := excelize.OpenFile(m.File)
  30. if err != nil {
  31. log.Println(err)
  32. return
  33. }
  34. defer Catch()
  35. rows, err := f.GetRows(m.Sheet)
  36. if err != nil {
  37. log.Println(err)
  38. return
  39. }
  40. //第一行表头,获取同步字段
  41. syncFileds := map[int]string{}
  42. lenRow := len(rows) - 2
  43. if lenRow > 2 {
  44. //if len(m.Fields) == 0 {
  45. //表头第二行
  46. for index, cell := range rows[1] {
  47. if len(m.Mfields) == 0 {
  48. syncFileds[index] = cell
  49. } else {
  50. fs := m.Mfields[cell]
  51. if fs != "" {
  52. syncFileds[index] = fs
  53. }
  54. }
  55. }
  56. //}
  57. } else {
  58. log.Println(m.File, "无数据")
  59. }
  60. //获取数据范围
  61. // max := m.Max
  62. // if m.Min > 0 && m.Max > m.Min {
  63. // if m.Min > lenRow {
  64. // log.Println(m.File, "数据索引超出范围", m.Min, m.Max, lenRow)
  65. // } else {
  66. // if m.Max > lenRow {
  67. // max = lenRow
  68. // }
  69. // rows = rows[m.Min:max]
  70. // }
  71. // }
  72. // 读取数据
  73. for _, row := range rows[2:] {
  74. data := map[string]any{}
  75. for index, colCell := range row {
  76. fs := syncFileds[index]
  77. if fs != "" && colCell != "" {
  78. f, d := ParseData(fs, colCell)
  79. data[f] = d
  80. }
  81. }
  82. //发送数据
  83. d.Send(data)
  84. }
  85. //数据遍历完成
  86. d.End()
  87. }