diff options
author | xuri <xuri.me@gmail.com> | 2020-09-01 00:40:56 +0800 |
---|---|---|
committer | xuri <xuri.me@gmail.com> | 2020-09-01 00:47:44 +0800 |
commit | 4177c1585e312bee00c1592af3df6423c366e806 (patch) | |
tree | a249e1531eeca4b1df5278bde206c4697ed7eee2 /excelize.go | |
parent | 88de2f8d510b0959bbb672b80656d207bd0bc927 (diff) |
Resolve #199, init password protection spreadsheet support
Diffstat (limited to 'excelize.go')
-rw-r--r-- | excelize.go | 47 |
1 files changed, 30 insertions, 17 deletions
diff --git a/excelize.go b/excelize.go index 75b0c13..6e2b849 100644 --- a/excelize.go +++ b/excelize.go @@ -56,15 +56,30 @@ type File struct { type charsetTranscoderFn func(charset string, input io.Reader) (rdr io.Reader, err error) -// OpenFile take the name of an spreadsheet file and returns a populated -// spreadsheet file struct for it. -func OpenFile(filename string) (*File, error) { +// Options define the options for open spreadsheet. +type Options struct { + Password string +} + +// OpenFile take the name of an spreadsheet file and returns a populated spreadsheet file struct +// for it. For example, open spreadsheet with password protection: +// +// f, err := excelize.OpenFile("Book1.xlsx", excelize.Options{Password: "password"}) +// if err != nil { +// return +// } +// +func OpenFile(filename string, opt ...Options) (*File, error) { file, err := os.Open(filename) if err != nil { return nil, err } defer file.Close() - f, err := OpenReader(file) + var option Options + for _, o := range opt { + option = o + } + f, err := OpenReader(file, option) if err != nil { return nil, err } @@ -91,25 +106,23 @@ func newFile() *File { // OpenReader read data stream from io.Reader and return a populated // spreadsheet file. -func OpenReader(r io.Reader) (*File, error) { +func OpenReader(r io.Reader, opt ...Options) (*File, error) { b, err := ioutil.ReadAll(r) if err != nil { return nil, err } - - zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b))) - if err != nil { - identifier := []byte{ - // checking protect workbook by [MS-OFFCRYPTO] - v20181211 3.1 FeatureIdentifier - 0x3c, 0x00, 0x00, 0x00, 0x4d, 0x00, 0x69, 0x00, 0x63, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x73, 0x00, - 0x6f, 0x00, 0x66, 0x00, 0x74, 0x00, 0x2e, 0x00, 0x43, 0x00, 0x6f, 0x00, 0x6e, 0x00, 0x74, 0x00, - 0x61, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x65, 0x00, 0x72, 0x00, 0x2e, 0x00, 0x44, 0x00, 0x61, 0x00, - 0x74, 0x00, 0x61, 0x00, 0x53, 0x00, 0x70, 0x00, 0x61, 0x00, 0x63, 0x00, 0x65, 0x00, 0x73, 0x00, - 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + if bytes.Contains(b, cryptoIdentifier) { + var option Options + for _, o := range opt { + option = o } - if bytes.Contains(b, identifier) { - return nil, errors.New("not support encrypted file currently") + b, err = Decrypt(b, &option) + if err != nil { + return nil, fmt.Errorf("decrypted file failed") } + } + zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b))) + if err != nil { return nil, err } |