2015-03-19 10:39:41 +01:00
|
|
|
package xls
|
|
|
|
|
|
|
|
import (
|
2018-04-05 15:28:01 +02:00
|
|
|
"bytes"
|
2015-03-19 10:39:41 +01:00
|
|
|
"io"
|
2018-04-05 15:28:01 +02:00
|
|
|
"io/ioutil"
|
2016-05-28 04:39:46 +02:00
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/extrame/ole2"
|
2015-03-19 10:39:41 +01:00
|
|
|
)
|
|
|
|
|
2015-09-30 04:40:01 +02:00
|
|
|
//Open one xls file
|
2015-03-19 10:39:41 +01:00
|
|
|
func Open(file string, charset string) (*WorkBook, error) {
|
2016-05-28 04:39:46 +02:00
|
|
|
if fi, err := os.Open(file); err == nil {
|
|
|
|
return OpenReader(fi, charset)
|
2015-03-19 10:39:41 +01:00
|
|
|
} else {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-05 15:28:01 +02:00
|
|
|
//OpenWithBuffer open one xls file with memory buffer
|
|
|
|
func OpenWithBuffer(file string, charset string) (*WorkBook, error) {
|
|
|
|
if fi, err := ioutil.ReadFile(file); err == nil {
|
|
|
|
return OpenReader(bytes.NewReader(fi), charset)
|
|
|
|
} else {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//OpenWithCloser open one xls file and return the closer
|
2018-03-22 02:25:17 +01:00
|
|
|
func OpenWithCloser(file string, charset string) (*WorkBook, io.Closer, error) {
|
|
|
|
if fi, err := os.Open(file); err == nil {
|
|
|
|
wb, err := OpenReader(fi, charset)
|
|
|
|
return wb, fi, err
|
|
|
|
} else {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-05 15:28:01 +02:00
|
|
|
//OpenReader open xls file from reader
|
2016-05-28 04:39:46 +02:00
|
|
|
func OpenReader(reader io.ReadSeeker, charset string) (wb *WorkBook, err error) {
|
2015-09-30 04:40:01 +02:00
|
|
|
var ole *ole2.Ole
|
2016-05-28 04:39:46 +02:00
|
|
|
if ole, err = ole2.Open(reader, charset); err == nil {
|
2015-09-30 04:40:01 +02:00
|
|
|
var dir []*ole2.File
|
|
|
|
if dir, err = ole.ListDir(); err == nil {
|
|
|
|
var book *ole2.File
|
2016-08-12 08:50:42 +02:00
|
|
|
var root *ole2.File
|
2015-09-30 04:40:01 +02:00
|
|
|
for _, file := range dir {
|
|
|
|
name := file.Name()
|
|
|
|
if name == "Workbook" {
|
|
|
|
book = file
|
|
|
|
// break
|
|
|
|
}
|
|
|
|
if name == "Book" {
|
|
|
|
book = file
|
|
|
|
// break
|
|
|
|
}
|
2016-08-12 08:50:42 +02:00
|
|
|
if name == "Root Entry" {
|
|
|
|
root = file
|
|
|
|
}
|
2015-09-30 04:40:01 +02:00
|
|
|
}
|
|
|
|
if book != nil {
|
2016-08-12 08:50:42 +02:00
|
|
|
wb = newWorkBookFromOle2(ole.OpenFile(book, root))
|
2015-09-30 04:40:01 +02:00
|
|
|
return
|
|
|
|
}
|
2015-03-19 10:39:41 +01:00
|
|
|
}
|
|
|
|
}
|
2015-09-30 04:40:01 +02:00
|
|
|
return
|
2015-03-19 10:39:41 +01:00
|
|
|
}
|