Merge pull request #275 from Zheaoli/master

Add Support for WriteTo Buffer
This commit is contained in:
xuri 2018-10-12 10:36:19 +08:00 committed by GitHub
commit d8a34af384
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 8 deletions

View File

@ -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) {

20
file.go
View File

@ -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()
}