Skip to content

Commit 7bf0bbb

Browse files
author
岑思华
committed
Add custom ZIP writer support for WriteToBuffer function
1 parent b372bd3 commit 7bf0bbb

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

file.go

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import (
1717
"encoding/binary"
1818
"encoding/xml"
1919
"io"
20+
"io/fs"
2021
"math"
2122
"os"
2223
"path/filepath"
@@ -136,8 +137,22 @@ func (f *File) WriteTo(w io.Writer, opts ...Options) (int64, error) {
136137
// WriteToBuffer provides a function to get bytes.Buffer from the saved file,
137138
// and it allocates space in memory. Be careful when the file size is large.
138139
func (f *File) WriteToBuffer() (*bytes.Buffer, error) {
140+
return f.WriteToBufferCustomZIP(func(w io.Writer) ZipWriter { return zip.NewWriter(w) })
141+
}
142+
143+
type ZipWriter interface {
144+
Create(name string) (io.Writer, error)
145+
AddFS(fsys fs.FS) error
146+
Close() error
147+
}
148+
149+
// WriteToBufferCustomZIP provides a function to write to a buffer using a custom ZIP writer
150+
// factory. This allows for custom ZIP compression implementations to be used when saving
151+
// the spreadsheet to memory. The factory function should return a zipWriter interface
152+
// that will be used to create the final ZIP archive.
153+
func (f *File) WriteToBufferCustomZIP(factory func(io.Writer) ZipWriter) (*bytes.Buffer, error) {
139154
buf := new(bytes.Buffer)
140-
zw := zip.NewWriter(buf)
155+
zw := factory(buf)
141156

142157
if err := f.writeToZip(zw); err != nil {
143158
_ = zw.Close()
@@ -158,8 +173,8 @@ func (f *File) WriteToBuffer() (*bytes.Buffer, error) {
158173
return buf, nil
159174
}
160175

161-
// writeToZip provides a function to write to zip.Writer
162-
func (f *File) writeToZip(zw *zip.Writer) error {
176+
// writeToZip provides a function to write to zipWriter
177+
func (f *File) writeToZip(zw ZipWriter) error {
163178
f.calcChainWriter()
164179
f.commentsWriter()
165180
f.contentTypesWriter()

0 commit comments

Comments
 (0)