2016-08-30 11:51:31 +08:00
|
|
|
package excelize
|
|
|
|
|
|
|
|
import (
|
|
|
|
"archive/zip"
|
|
|
|
"bytes"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
2017-01-18 16:05:01 +08:00
|
|
|
// CreateFile provides function to create new file by default template. For
|
|
|
|
// example:
|
|
|
|
//
|
|
|
|
// xlsx := CreateFile()
|
|
|
|
//
|
2016-09-05 16:37:15 +08:00
|
|
|
func CreateFile() *File {
|
2016-09-05 10:44:32 +08:00
|
|
|
file := make(map[string]string)
|
2017-01-18 14:47:23 +08:00
|
|
|
file["_rels/.rels"] = templateRels
|
|
|
|
file["docProps/app.xml"] = templateDocpropsApp
|
|
|
|
file["docProps/core.xml"] = templateDocpropsCore
|
|
|
|
file["xl/_rels/workbook.xml.rels"] = templateWorkbookRels
|
|
|
|
file["xl/theme/theme1.xml"] = templateTheme
|
|
|
|
file["xl/worksheets/sheet1.xml"] = templateSheet
|
|
|
|
file["xl/styles.xml"] = templateStyles
|
|
|
|
file["xl/workbook.xml"] = templateWorkbook
|
|
|
|
file["[Content_Types].xml"] = templateContentTypes
|
2016-09-05 16:37:15 +08:00
|
|
|
return &File{
|
|
|
|
XLSX: file,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-18 16:05:01 +08:00
|
|
|
// Save provides function override the xlsx file with origin path.
|
2016-09-05 16:37:15 +08:00
|
|
|
func (f *File) Save() error {
|
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
w := zip.NewWriter(buf)
|
|
|
|
for path, content := range f.XLSX {
|
|
|
|
f, err := w.Create(path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
_, err = f.Write([]byte(content))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
err := w.Close()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
file, err := os.OpenFile(f.Path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
buf.WriteTo(file)
|
|
|
|
return err
|
2016-08-30 11:51:31 +08:00
|
|
|
}
|
|
|
|
|
2017-01-18 16:05:01 +08:00
|
|
|
// WriteTo provides function to create or update to an xlsx file at the provided
|
|
|
|
// path.
|
2016-09-05 16:37:15 +08:00
|
|
|
func (f *File) WriteTo(name string) error {
|
2016-08-30 11:51:31 +08:00
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
w := zip.NewWriter(buf)
|
2016-09-05 16:37:15 +08:00
|
|
|
for path, content := range f.XLSX {
|
2016-09-05 10:44:32 +08:00
|
|
|
f, err := w.Create(path)
|
2016-08-30 11:51:31 +08:00
|
|
|
if err != nil {
|
2016-09-02 10:28:29 +08:00
|
|
|
return err
|
2016-08-30 11:51:31 +08:00
|
|
|
}
|
2016-09-05 10:44:32 +08:00
|
|
|
_, err = f.Write([]byte(content))
|
2016-08-30 11:51:31 +08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
err := w.Close()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-09-05 16:37:15 +08:00
|
|
|
file, err := os.OpenFile(name, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
|
2016-08-30 11:51:31 +08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-09-05 16:37:15 +08:00
|
|
|
buf.WriteTo(file)
|
2016-08-30 11:51:31 +08:00
|
|
|
return err
|
|
|
|
}
|