excelize/file.go

88 lines
1.9 KiB
Go
Raw Normal View History

2016-08-30 11:51:31 +08:00
package excelize
import (
"archive/zip"
"bytes"
2017-03-12 20:38:26 +08:00
"encoding/xml"
2017-02-17 02:25:55 +08:00
"fmt"
"io"
2016-08-30 11:51:31 +08:00
"os"
)
// CreateFile provides function to create new file by default template. For
// example:
//
// xlsx := CreateFile()
//
func CreateFile() *File {
file := make(map[string]string)
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
return &File{
2017-03-12 20:38:26 +08:00
XLSX: file,
Sheet: make(map[string]*xlsxWorksheet),
}
}
// 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")
}
2017-02-17 02:25:55 +08:00
return f.WriteTo(f.Path)
2016-08-30 11:51:31 +08:00
}
// WriteTo provides function to create or update to an xlsx file at the provided
// path.
func (f *File) WriteTo(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 {
2016-08-30 11:51:31 +08:00
buf := new(bytes.Buffer)
2017-02-17 02:25:55 +08:00
zw := zip.NewWriter(buf)
2017-03-12 20:38:26 +08:00
for path, sheet := range f.Sheet {
if sheet == nil {
continue
}
output, err := xml.Marshal(sheet)
if err != nil {
return err
}
f.saveFileList(path, replaceWorkSheetsRelationshipsNameSpace(string(output)))
}
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 err
2016-08-30 11:51:31 +08:00
}
2017-02-17 02:25:55 +08:00
_, err = fi.Write([]byte(content))
2016-08-30 11:51:31 +08:00
if err != nil {
return err
}
}
2017-02-17 02:25:55 +08:00
err := zw.Close()
2016-08-30 11:51:31 +08:00
if err != nil {
return err
}
2017-02-17 02:25:55 +08:00
if _, err := buf.WriteTo(w); err != nil {
2016-08-30 11:51:31 +08:00
return err
}
2017-02-17 02:25:55 +08:00
return nil
2016-08-30 11:51:31 +08:00
}