feat: add new function and refactor writeto action

* add new exported function to get Excel file content buffer

* refactor the WriteTo function
formula
lizheao 6 years ago
parent f0234e6c08
commit 2be4d45c62

@ -135,6 +135,10 @@ func TestOpenFile(t *testing.T) {
if err != nil { if err != nil {
t.Log(err) t.Log(err)
} }
_, err = xlsx.WriteToBuffer()
if err != nil {
t.Error(err)
}
} }
func TestAddPicture(t *testing.T) { func TestAddPicture(t *testing.T) {

@ -76,6 +76,15 @@ func (f *File) Write(w io.Writer) error {
// WriteTo implements io.WriterTo to write the file. // WriteTo implements io.WriterTo to write the file.
func (f *File) WriteTo(w io.Writer) (int64, error) { 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) buf := new(bytes.Buffer)
zw := zip.NewWriter(buf) zw := zip.NewWriter(buf)
f.contentTypesWriter() f.contentTypesWriter()
@ -86,17 +95,12 @@ func (f *File) WriteTo(w io.Writer) (int64, error) {
for path, content := range f.XLSX { for path, content := range f.XLSX {
fi, err := zw.Create(path) fi, err := zw.Create(path)
if err != nil { if err != nil {
return 0, err return buf, err
} }
_, err = fi.Write(content) _, err = fi.Write(content)
if err != nil { if err != nil {
return 0, err return buf, err
} }
} }
err := zw.Close() return buf, zw.Close()
if err != nil {
return 0, err
}
return buf.WriteTo(w)
} }

Loading…
Cancel
Save