excelize/file.go

93 lines
2.4 KiB
Go
Raw Normal View History

2016-08-30 11:51:31 +08:00
package excelize
import (
"archive/zip"
"bytes"
2017-02-17 02:25:55 +08:00
"fmt"
"io"
2016-08-30 11:51:31 +08:00
"os"
)
// NewFile provides function to create new file by default template. For
// example:
//
// xlsx := NewFile()
//
func NewFile() *File {
2018-05-07 16:12:51 +08:00
file := make(map[string][]byte)
file["_rels/.rels"] = []byte(XMLHeader + templateRels)
file["docProps/app.xml"] = []byte(XMLHeader + templateDocpropsApp)
file["docProps/core.xml"] = []byte(XMLHeader + templateDocpropsCore)
file["xl/_rels/workbook.xml.rels"] = []byte(XMLHeader + templateWorkbookRels)
file["xl/theme/theme1.xml"] = []byte(XMLHeader + templateTheme)
file["xl/worksheets/sheet1.xml"] = []byte(XMLHeader + templateSheet)
file["xl/styles.xml"] = []byte(XMLHeader + templateStyles)
file["xl/workbook.xml"] = []byte(XMLHeader + templateWorkbook)
file["[Content_Types].xml"] = []byte(XMLHeader + templateContentTypes)
f := &File{
sheetMap: make(map[string]string),
Sheet: make(map[string]*xlsxWorksheet),
SheetCount: 1,
XLSX: file,
}
f.ContentTypes = f.contentTypesReader()
f.Styles = f.stylesReader()
f.WorkBook = f.workbookReader()
f.WorkBookRels = f.workbookRelsReader()
f.Sheet["xl/worksheets/sheet1.xml"] = f.workSheetReader("Sheet1")
f.sheetMap["Sheet1"] = "xl/worksheets/sheet1.xml"
return f
}
// Save provides function to override the xlsx file with origin path.
func (f *File) Save() error {
2017-02-17 02:25:55 +08:00
if f.Path == "" {
return fmt.Errorf("No path defined for file, consider File.WriteTo or File.Write")
}
return f.SaveAs(f.Path)
2016-08-30 11:51:31 +08:00
}
// SaveAs provides function to create or update to an xlsx file at the provided
// path.
func (f *File) SaveAs(name string) error {
2017-02-17 02:25:55 +08:00
file, err := os.OpenFile(name, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
if err != nil {
return err
}
defer file.Close()
return f.Write(file)
}
// Write provides function to write to an io.Writer.
func (f *File) Write(w io.Writer) error {
_, err := f.WriteTo(w)
return err
}
// WriteTo implements io.WriterTo to write the file.
func (f *File) WriteTo(w io.Writer) (int64, error) {
2016-08-30 11:51:31 +08:00
buf := new(bytes.Buffer)
2017-02-17 02:25:55 +08:00
zw := zip.NewWriter(buf)
f.contentTypesWriter()
f.workbookWriter()
f.workbookRelsWriter()
f.worksheetWriter()
f.styleSheetWriter()
for path, content := range f.XLSX {
2017-02-17 02:25:55 +08:00
fi, err := zw.Create(path)
2016-08-30 11:51:31 +08:00
if err != nil {
return 0, err
2016-08-30 11:51:31 +08:00
}
_, err = fi.Write(content)
2016-08-30 11:51:31 +08:00
if err != nil {
return 0, err
2016-08-30 11:51:31 +08:00
}
}
2017-02-17 02:25:55 +08:00
err := zw.Close()
2016-08-30 11:51:31 +08:00
if err != nil {
return 0, err
2016-08-30 11:51:31 +08:00
}
2017-02-17 02:25:55 +08:00
return buf.WriteTo(w)
2016-08-30 11:51:31 +08:00
}