diff --git a/excelize_test.go b/excelize_test.go index 9f738f3..b24e45b 100644 --- a/excelize_test.go +++ b/excelize_test.go @@ -135,6 +135,10 @@ func TestOpenFile(t *testing.T) { if err != nil { t.Log(err) } + _, err = xlsx.WriteToBuffer() + if err != nil { + t.Error(err) + } } func TestAddPicture(t *testing.T) { diff --git a/file.go b/file.go index 5bfed39..1f69005 100644 --- a/file.go +++ b/file.go @@ -76,6 +76,15 @@ func (f *File) Write(w io.Writer) error { // WriteTo implements io.WriterTo to write the file. func (f *File) WriteTo(w io.Writer) (int64, error) { + buf, err := f.WriteToBuffer() + if err != nil { + return 0, err + } + return buf.WriteTo(w) +} + +// WriteToBuffer provides a function to get bytes.Buffer from the saved file. +func (f *File) WriteToBuffer() (*bytes.Buffer, error) { buf := new(bytes.Buffer) zw := zip.NewWriter(buf) f.contentTypesWriter() @@ -86,17 +95,12 @@ func (f *File) WriteTo(w io.Writer) (int64, error) { for path, content := range f.XLSX { fi, err := zw.Create(path) if err != nil { - return 0, err + return buf, err } _, err = fi.Write(content) if err != nil { - return 0, err + return buf, err } } - err := zw.Close() - if err != nil { - return 0, err - } - - return buf.WriteTo(w) + return buf, zw.Close() }