12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- package xvdoc
- import (
- "encoding/json"
- "fmt"
- "io"
- "os"
- "github.com/xuri/excelize/v2"
- )
- func ImportXLSXFromFile(fileName string) (res []*Sheet, err error) {
- var f *os.File
- if f, err = os.Open(fileName); err == nil {
- res, err = ImportXLSX(f)
- f.Close()
- }
- return
- }
- func ImportXLSX(r io.Reader) (res []*Sheet, err error) {
- var f *excelize.File
- if f, err = excelize.OpenReader(r); err != nil {
- return
- }
- res = make([]*Sheet, 0, f.SheetCount)
- for _, sheetName := range f.GetSheetMap() {
- sheet := Sheet{name: sheetName}
- if sheet.rows, err = f.GetRows(sheet.name); err != nil {
- return
- }
- res = append(res, &sheet)
- }
- return
- }
- func ImportXLSXToJSON(r io.Reader) (res []byte, err error) {
- var sheets []*Sheet
- if sheets, err = ImportXLSX(r); err != nil {
- return
- }
- res, err = json.Marshal(sheets)
- return
- }
- func ImportXLSXToJSONFromFile(fileName string) (res []byte, err error) {
- var f *os.File
- if f, err = os.Open(fileName); err == nil {
- res, err = ImportXLSXToJSON(f)
- f.Close()
- }
- return
- }
- type Sheet struct {
- name string
- rows [][]string
- }
- func (s *Sheet) String() string {
- return fmt.Sprint(s.name, s.rows)
- }
- func (s *Sheet) MarshalJSON() ([]byte, error) {
- m := map[string]interface{}{
- "name": s.name,
- "rows": s.rows,
- }
- return json.Marshal(m)
- }
|