Skip to content

Commit

Permalink
Func. appending an existing sheet to a file (#1)
Browse files Browse the repository at this point in the history
* Func. appending an existing sheet to a file

In cases where Sheet(s) is created before File

* added AppendSheet tests

* Fix appending of instances instead of copies

* Fix appending of instances instead of copies
  • Loading branch information
tokyis committed Jan 16, 2017
1 parent 2c69b0c commit 915b193
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
13 changes: 13 additions & 0 deletions file.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,19 @@ func (f *File) AddSheet(sheetName string) (*Sheet, error) {
return sheet, nil
}

// Appends an existing Sheet, with the provided name, to a File
func (f *File) AppendSheet(sheet Sheet, sheetName string) (*Sheet, error) {
if _, exists := f.Sheet[sheetName]; exists {
return nil, fmt.Errorf("duplicate sheet name '%s'.", sheetName)
}
sheet.Name = sheetName
sheet.File = f
sheet.Selected = len(f.Sheets) == 0
f.Sheet[sheetName] = &sheet
f.Sheets = append(f.Sheets, &sheet)
return &sheet, nil
}

func (f *File) makeWorkbook() xlsxWorkbook {
return xlsxWorkbook{
FileVersion: xlsxFileVersion{AppName: "Go XLSX"},
Expand Down
23 changes: 23 additions & 0 deletions file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,29 @@ func (l *FileSuite) TestAddSheetWithDuplicateName(c *C) {
c.Assert(err, ErrorMatches, "duplicate sheet name 'MySheet'.")
}

// Test that we can append a sheet to a File
func (l *FileSuite) TestAppendSheet(c *C) {
var f *File

f = NewFile()
s := Sheet{}
sheet, err := f.AppendSheet(s, "MySheet")
c.Assert(err, IsNil)
c.Assert(sheet, NotNil)
c.Assert(len(f.Sheets), Equals, 1)
c.Assert(f.Sheet["MySheet"], Equals, sheet)
}

// Test that AppendSheet returns an error if you try to add two sheets with the same name
func (l *FileSuite) TestAppendSheetWithDuplicateName(c *C) {
f := NewFile()
s := Sheet{}
_, err := f.AppendSheet(s, "MySheet")
c.Assert(err, IsNil)
_, err = f.AppendSheet(s, "MySheet")
c.Assert(err, ErrorMatches, "duplicate sheet name 'MySheet'.")
}

// Test that we can get the Nth sheet
func (l *FileSuite) TestNthSheet(c *C) {
var f *File
Expand Down

0 comments on commit 915b193

Please sign in to comment.