import.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package xvdoc
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "os"
  7. "github.com/xuri/excelize/v2"
  8. )
  9. func ImportXLSXFromFile(fileName string) (res []*Sheet, err error) {
  10. var f *os.File
  11. if f, err = os.Open(fileName); err == nil {
  12. res, err = ImportXLSX(f)
  13. f.Close()
  14. }
  15. return
  16. }
  17. func ImportXLSX(r io.Reader) (res []*Sheet, err error) {
  18. var f *excelize.File
  19. if f, err = excelize.OpenReader(r); err != nil {
  20. return
  21. }
  22. res = make([]*Sheet, 0, f.SheetCount)
  23. for _, sheetName := range f.GetSheetMap() {
  24. sheet := Sheet{name: sheetName}
  25. if sheet.rows, err = f.GetRows(sheet.name); err != nil {
  26. return
  27. }
  28. res = append(res, &sheet)
  29. }
  30. return
  31. }
  32. func ImportXLSXToJSON(r io.Reader) (res []byte, err error) {
  33. var sheets []*Sheet
  34. if sheets, err = ImportXLSX(r); err != nil {
  35. return
  36. }
  37. res, err = json.Marshal(sheets)
  38. return
  39. }
  40. func ImportXLSXToJSONFromFile(fileName string) (res []byte, err error) {
  41. var f *os.File
  42. if f, err = os.Open(fileName); err == nil {
  43. res, err = ImportXLSXToJSON(f)
  44. f.Close()
  45. }
  46. return
  47. }
  48. type Sheet struct {
  49. name string
  50. rows [][]string
  51. }
  52. func (s *Sheet) String() string {
  53. return fmt.Sprint(s.name, s.rows)
  54. }
  55. func (s *Sheet) MarshalJSON() ([]byte, error) {
  56. m := map[string]interface{}{
  57. "name": s.name,
  58. "rows": s.rows,
  59. }
  60. return json.Marshal(m)
  61. }