spreadsheet: clear temp files when closing sheets

We don't bother keeping all files in memory as there
can be several, and we don't need them all.  This just
adds a Close() method that can be used to ensure the
temporary files are removed.
This commit is contained in:
Todd 2017-10-02 18:15:59 -05:00
parent 56e9890d9f
commit 76cd395f6a
2 changed files with 26 additions and 3 deletions

View File

@ -8,6 +8,8 @@
package spreadsheet package spreadsheet
import ( import (
"runtime"
"baliance.com/gooxml" "baliance.com/gooxml"
"baliance.com/gooxml/common" "baliance.com/gooxml/common"
"baliance.com/gooxml/schema/soo/sml" "baliance.com/gooxml/schema/soo/sml"
@ -18,6 +20,8 @@ func New() *Workbook {
wb := &Workbook{} wb := &Workbook{}
wb.x = sml.NewWorkbook() wb.x = sml.NewWorkbook()
runtime.SetFinalizer(wb, workbookFinalizer)
wb.AppProperties = common.NewAppProperties() wb.AppProperties = common.NewAppProperties()
wb.CoreProperties = common.NewCoreProperties() wb.CoreProperties = common.NewCoreProperties()
wb.StyleSheet = NewStyleSheet(wb) wb.StyleSheet = NewStyleSheet(wb)

View File

@ -15,6 +15,7 @@ import (
"image/jpeg" "image/jpeg"
"io" "io"
"os" "os"
"strings"
"time" "time"
"baliance.com/gooxml" "baliance.com/gooxml"
@ -29,6 +30,9 @@ import (
"baliance.com/gooxml/schema/soo/sml" "baliance.com/gooxml/schema/soo/sml"
) )
// ErrorNotFound is returned when something is not found
var ErrorNotFound = errors.New("not found")
// Workbook is the top level container item for a set of spreadsheets. // Workbook is the top level container item for a set of spreadsheets.
type Workbook struct { type Workbook struct {
common.DocBase common.DocBase
@ -552,11 +556,26 @@ func (wb *Workbook) Protection() WorkbookProtection {
return WorkbookProtection{wb.x.WorkbookProtection} return WorkbookProtection{wb.x.WorkbookProtection}
} }
func (wb *Workbook) GetSheet(name string) Sheet { // GetSheet returns a sheet by name, or an error if a sheet by the given name
// was not found.
func (wb *Workbook) GetSheet(name string) (Sheet, error) {
for _, s := range wb.Sheets() { for _, s := range wb.Sheets() {
if s.Name() == name { if s.Name() == name {
return s return s, nil
} }
} }
return Sheet{} return Sheet{}, ErrorNotFound
}
func workbookFinalizer(wb *Workbook) {
wb.Close()
}
// Close closes the workbook, removing any temporary files that might have been
// created when opening a document.
func (wb *Workbook) Close() error {
if wb.TmpPath != "" && strings.HasPrefix(wb.TmpPath, os.TempDir()) {
return os.RemoveAll(wb.TmpPath)
}
return nil
} }