Browse Source

Func. appending an existing sheet to a file (#1)

* 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
tokyis 9 years ago
parent
commit
f2941942f4
2 changed files with 36 additions and 0 deletions
  1. 13 0
      file.go
  2. 23 0
      file_test.go

+ 13 - 0
file.go

@@ -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"},

+ 23 - 0
file_test.go

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